Skip to content

Instantly share code, notes, and snippets.

@fresky
Created December 4, 2012 13:39
Show Gist options
  • Save fresky/4203965 to your computer and use it in GitHub Desktop.
Save fresky/4203965 to your computer and use it in GitHub Desktop.
Example code to show can NOT use Base* for the array of Sub
#include <iostream>
#include <assert.h>
using namespace std;
class B;
class A
{
public:
A();
~A();
int aa;
};
class B:public A
{
public:
B();
~B();
int bb;
};
A::A()
{
cout<<"A"<<" ";
aa=1;
}
A::~A()
{
cout<<"~A"<<" ";
aa=-1;
}
B::B()
{
cout<<"B"<<" ";
bb=2;
}
B::~B()
{
cout<<"~B"<<" ";
bb=-2;
}
int main(int argc, char* argv[])
{
cout<<"size of A: "<<sizeof(A)<<endl;
cout<<"size of B: "<<sizeof(B)<<endl;
A* aarray = new B[10];
cout<<endl<<endl<<"aa value of A* is:"<<endl;
for (int i = 0; i < 10; i++)
{
cout<<aarray[i].aa<<", ";
}
cout<<endl;
B* baaray = (B*)aarray;
cout<<endl<<"aa value of B* is:"<<endl;
for (int i = 0; i < 10; i++)
{
cout<<baaray[i].aa<<", ";
}
cout<<endl<<endl;
delete[] aarray;
cout<<endl<<endl<<"After delete[]"<<endl;
cout<<endl<<"aa value of A* is:"<<endl;
for (int i = 0; i < 10; i++)
{
cout<<aarray[i].aa<<", ";
}
cout<<endl;
baaray = (B*)aarray;
cout<<endl<<"aa value of B* is:"<<endl;
for (int i = 0; i < 10; i++)
{
cout<<baaray[i].aa<<", ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment