R
rahul8143
hello,
I have got following code form some university site that has C++
tutorials, i read it but has some problems
1)why the following code is rejected by the the compiler?
class Pet {
protected:
string _name;
public:
Pet(string name) : _name(name) {}
virtual string sound() const = 0;
virtual void speak() const {
cout << _name << ": " << sound() << "!\n";
}
};
class Dog : public Pet {
public:
Dog(string name) : Pet(name) {}
string sound() const { return "woof"; }
void speak() const { // virtual is optional
Pet::speak();
cout << '(' << _name << " wags tail)\n";
}
};
class Cat : public Pet {
public:
Cat(string name) : Pet(name) {}
virtual string sound() const { return "miao"; }
};
void chase(Pet &x, Cat &y) { ... }
void chase(Dog &x, Pet &y) { ... }
int main() {
Dog buster;
Cat tom;
chase(buster, tom); // ambiguous error!
}
2)why slicing doesnot occur in following declarations
Cat felix;
Pet *p = &felix;
p->speak(); // miao
I have got following code form some university site that has C++
tutorials, i read it but has some problems
1)why the following code is rejected by the the compiler?
class Pet {
protected:
string _name;
public:
Pet(string name) : _name(name) {}
virtual string sound() const = 0;
virtual void speak() const {
cout << _name << ": " << sound() << "!\n";
}
};
class Dog : public Pet {
public:
Dog(string name) : Pet(name) {}
string sound() const { return "woof"; }
void speak() const { // virtual is optional
Pet::speak();
cout << '(' << _name << " wags tail)\n";
}
};
class Cat : public Pet {
public:
Cat(string name) : Pet(name) {}
virtual string sound() const { return "miao"; }
};
void chase(Pet &x, Cat &y) { ... }
void chase(Dog &x, Pet &y) { ... }
int main() {
Dog buster;
Cat tom;
chase(buster, tom); // ambiguous error!
}
2)why slicing doesnot occur in following declarations
Cat felix;
Pet *p = &felix;
p->speak(); // miao