So I’m about finishing up prata’s C++ primer and I’m u to RTTI. He showed a line of downcasting and just said it’s wrong but I want to see a better example.
class Grand
{
private:
int hold;
public:
Grand(int h=0) : hold(h) {}
virtual void Speak() const { cout << "I am a grand class\n";}
virtual int Value() const {return hold; }
void Gah() const {cout << "ok" << endl;}
};
class Superb : public Grand
{
public:
Superb(int h = 0) : Grand(h){}
void Speak() const {cout << "I am a superb class!!\n";}
virtual void Say() const
{ cout << "I hold the superb value of " << Value() << "!\n";}
void Sah() const { cout << "Noak" << endl;}
};
class Magnificent : public Superb
{
private:
char ch;
public:
int hour;
Magnificent(int h = 0, char c = 'A') : Superb (h), ch(c){}
void Speak() const {cout << "I am a magnificent class!!!\n";}
void Say() const {cout << "I hold the character " << ch <<
"and the integer " << Value() << "!\n";}
void Mah() const {cout << "Ok" << endl;}
};
Grand * GetOne();
int _tmain(int argc, _TCHAR* argv[])
{
/*
srand(time(0));
Grand * pg;
Superb * ps;
*/
Grand * pg = new Grand;
Grand * ps = new Superb;
Grand * pm = new Magnificent;
Magnificent * ps2 = (Magnificent *)pg;
ps2->Gah();
cout << ps2->hour << endl;
system("pause");
}
So above, I’m casting a base to a derived which is overall not to be done. However, in this example, what am I really limited to? When I am casting pg, I still have access through ps2 to all of the grand/superb/magnificent properties and methods. In other words, nothing fails here. Can anyone give me an example or add something to the code which will clearly show to me how assigning a base to a derived can mess things up?
Do not use C style casts.
They are not safe. C++ has introduced 4 new casts the one you are looking for is dynamic_cast<>
When you use a C style cast you are telling the compiler to ignore all the rules and do what you tell it (which the compiler is happy to do). There is no checking done to make sure what you are doing makes any sense.
The C++ style casts are much more limiting and each does a specific range of casting. The dynamic_cast is used to cast up and down the class hierarchy.