I have an abstract base class and 2 different classes that implements a virtual function from the baseclass.
I put these in an array, and for “derived1” class this works.
If I however make an array of “derived2” class that has some extra private variables, the code will compile but errors at runtime.
#include <iostream>
class base{
protected:
int inner_a;
int inner_b;
public:
void setInner(int a,int b){inner_a=a;inner_b=b;};
virtual int doStuff()=0;
};
class derived1: public base{
public:
virtual int doStuff();
};
class derived2: public base{
private:
int tmpVar;//works if I remove
public:
int doStuff();
};
int derived2::doStuff(){
return inner_a-inner_b;
}
int derived1::doStuff(){
return inner_a+inner_b;
}
int main(){
base *classAry1 = new derived1[3];//this works
base *classAry2 = new derived2[2];//derived2 has extra private variables
classAry1[0].setInner(1,3);
classAry1[1].setInner(10,7);
std::cout <<classAry1[0].doStuff() <<std::endl;;
std::cout <<classAry1[1].doStuff() <<std::endl;
classAry2[0].setInner(1,3);
classAry2[1].setInner(10,7);
std::cout <<classAry2[0].doStuff() <<std::endl;;
std::cout <<classAry2[1].doStuff() <<std::endl;
return 0;
}
Can anyone help me, on how to put deriveded classes in a std array?
Thanks
edit:
The code segfaults, and valgrind tells me
-2
==25096== Use of uninitialised value of size 8
==25096== at 0x400AC9: main (abc.cpp:52)
==25096==
==25096== Invalid read of size 8
==25096== at 0x400AC9: main (abc.cpp:52)
==25096== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==25096==
==25096==
==25096== Process terminating with default action of signal 11 (SIGSEGV)
==25096== Access not within mapped region at address 0x0
==25096== at 0x400AC9: main (abc.cpp:52)
An array of
derived1objects (orderived2objects) cannot be interpreted as an array ofbaseobjects. Arrays are not polymorphic. Only standalone object can be polymorphic, i.e.derived1has IS-A relationship withbase. Butarray of derived1does not have IS-A relationship witharray of base. Neither of your arrays (neitherclassAry1norclassAry2) can really “work”.In other words, this
already does not make any sense, even though it is formally well-formed code.
The first array “appears to work” just by pure accident. The behavior of your code is undefined, even when you work with
classAry1.If you want to have an array (or a container) that stores polymorphic entities, you have to store pointers to actual objects in that array, instead of storing the actual objects themselves.
In your specific case, the code can be rewritten in the following way. (It doesn’t look very nice and I’m just doing it to illustrate the principle, since without knowing your full intent it is hard to choose the best approach)