I was trying the idea of casting in C++ using Visual Studio C++ 2010 Express and the use of dynamic_cast. But somehow, when I run it, an cat object can actually perform dog behaviour.
Seem like Dog d = (Dog)aa; got the compiler confused. Any advice?
Below is my code.
`
#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
string name ;
Animal(string n) : name(n) {cout << "construct animal " << name << endl ; }
Animal() : name("none") { };
virtual string getName() { return name ; }
virtual ~Animal() { cout << "destruct animal " << name << endl ; }
};
class Dog: public Animal{
public:
Dog() :Animal("") { }
Dog(string n): Animal(n) {
cout << "construct Dog" << endl ;
}
void dogStuff() { cout << "hello woof...."; }
};
class Cat: public Animal{
public:
Cat() :Animal("") { }
Cat(string n): Animal(n) {
cout << "construct Cat" << endl ;
}
void catStuff() { cout << "hello meow...."; }
};
int main() {
Animal *aa = new Cat("Catty"); // cat upcasting to animal
Dog *d = (Dog*)aa; // animal downcasting to dog. ???
cout << d->getName() << endl;
d->dogStuff();
Dog* dog = dynamic_cast<Dog*>(d) ;
if(dog) {
cout << "valid cast" << endl ;
dog->dogStuff();
cout << dog->getName();
}else
cout << "invalid cast" << endl ;
int i ;
cin >> i ;
return 0;
}
output
construct animal Catty
construct Cat
Catty
hello woof....valid cast
hello woof....Catty
`