#include <iostream>
usingnamespace std;
class superclass;
class subclass1;
class subclass2;
class superclass
{
public:
unsignedint a;
superclass(){a=1;}
virtual ~superclass(){}
};
class subclass1 : public superclass
{
public :
unsignedint b;
subclass1(){b=2;}
~subclass1(){}
};
class subclass2 : public superclass
{
public :
unsignedint c;
subclass2(){c=3;}
~subclass2(){}
};
class master
{
public:
superclass **superman;
master()
{
superman=new superclass*[2];
subclass1 s1;
s1.b=8;
*superman[0]=(superclass)s1;
subclass2 s2;
s2.c=9;
*superman[1]=(superclass)s2;
}
~master()
{
delete[]superman;
}
};
int main()
{
try{
master m;
cout<<"1"<<endl;
subclass1 *s1=dynamic_cast<subclass1*>(m.superman[0]);
subclass2 *s2=dynamic_cast<subclass2*>(m.superman[1]);
cout<<"2"<<endl;
cout<<"hello "<<" "<<" "<<s1->b<<endl;
}catch(exception e){e.what();}
return 0;
}
As you can see I want to create a dynamicaly alocated storage of references to a parent class each of which can then point to a child class, how ever I do not know how to extract the child class out again from that array so i may access its variable b.I am sure I am missing something small, any help would be great.
PS: I could not find a similar question, but if it exists, please redirect me, also i would like a solution that does not require me to use vector or any inbuilt pre-existing library class.
Yes, this contains stuff you don't want to use. No, you aren't required to use those things, but it's convenient for me to do, since I don't want to reimplement them. If your compiler doesn't support C++11, you may have to do a little adjusting. The code you probably want to look at is in print