bilbobaggio
Technical User
I am having trouble with inheritance. here is a code sample. when i run the program it displays the first B object (ie the array of integers) but then i get an access violation. can anybody let me know what i am doing wrong? when i only create a pointer to a single B object it works fine. but trying to print an array of B's gives errors.
class A {
A(/*data*/){}
~A(){}
...
virtual ostream& print(ostream& out) const
{/*add to the stream*/};
...
}
class B : public A {
B(/*data*/) : A(/*data*/)
{ data = new int[5]; /*init array also*/}
~B(){delete [] data;}
int* data;
...
virtual ostream& print(ostream& out) const
{/*add data array to the stream*/};
...
}
main()
{
A* array;
array = new B[3];
for (int i=0; i<3; i++)
array.print(cout);
}
class A {
A(/*data*/){}
~A(){}
...
virtual ostream& print(ostream& out) const
{/*add to the stream*/};
...
}
class B : public A {
B(/*data*/) : A(/*data*/)
{ data = new int[5]; /*init array also*/}
~B(){delete [] data;}
int* data;
...
virtual ostream& print(ostream& out) const
{/*add data array to the stream*/};
...
}
main()
{
A* array;
array = new B[3];
for (int i=0; i<3; i++)
array.print(cout);
}