c++ - Problem allocating derived class array with new -
i have simple program
$ cat a.cpp #include <iostream> class myclass { public: virtual void check() { std::cout << "inside myclass\n"; } }; class myclass2: public myclass { public: int* a; virtual void check() { std::cout << "inside myclass2\n"; } }; int main() { myclass *w, *v; w = new myclass2[2]; v = new myclass2; std::cout << "calling w[0].check\n"; w[0].check(); std::cout << "calling v->check\n"; v->check(); std::cout << "calling w[1].check\n"; w[1].check(); } $ g++ a.cpp $ ./a.out calling w[0].check inside myclass2 calling v->check inside myclass2 calling w[1].check segmentation fault
i thought possible use new allocate derived class objects. also, v->check() seems work fine.
w = new myclass2[2];
this creates array of 2 myclass2
objects. of type myclass2[2]
. new expression returns pointer initial element of array , assign pointer w
.
w[1].check();
this treats w
pointer array of myclass
objects, not array of myclass2
objects.
you cannot treat array of derived class objects if array of base class objects. if want able use derived-class objects, need array of pointers:
myclass** w = new myclass*[2]; w[0] = new myclass2; w[1] = new myclass2;
Comments
Post a Comment