Y
Yin99
I have the following code (Mammal base class, Dog inherits from
Mammal):
Dog *spot= new Dog;
spot->Speak();
Mammal *fido = dynamic_cast<Mammal*>(spot);
fido->Speak();
Dog *bandit = dynamic_cast<Dog*>(fido);
bandit->Speak();
I would expect the output:
Woof!
Mammal speak!
Woof!
Instead, I get the output:
Woof!
Woof!
Woof!
Since Speak is a virtual method, shouldn't it know when it is casted to
a Mammal,
and call the Speak method in that class? Thanks,
Yin99
--- header files -----
class Mammal
{
public:
void Move() const;
virtual void Speak() const;
Mammal();
virtual ~Mammal();
private:
int itsAge;
};
class Dog : public Mammal
{
public:
void WagTail();
void Speak() const;
void Move() const;
Dog();
virtual ~Dog();
};
Mammal):
Dog *spot= new Dog;
spot->Speak();
Mammal *fido = dynamic_cast<Mammal*>(spot);
fido->Speak();
Dog *bandit = dynamic_cast<Dog*>(fido);
bandit->Speak();
I would expect the output:
Woof!
Mammal speak!
Woof!
Instead, I get the output:
Woof!
Woof!
Woof!
Since Speak is a virtual method, shouldn't it know when it is casted to
a Mammal,
and call the Speak method in that class? Thanks,
Yin99
--- header files -----
class Mammal
{
public:
void Move() const;
virtual void Speak() const;
Mammal();
virtual ~Mammal();
private:
int itsAge;
};
class Dog : public Mammal
{
public:
void WagTail();
void Speak() const;
void Move() const;
Dog();
virtual ~Dog();
};