Reputation: 11
I have an array of pointers, that point to derived class objects.
The code always calls Base::func()
, even though it is virtual in the base class,
and in the array there are only derived class objects.
double Base::func2(){
...
for(unsigned i=0;i<elementNum;i++){
array[i]->func1();
...
}
The Base with the virtual function:
class Base{
...
public:
virtual double func1()
};
The Derived class:
class Derived: public Base{
...
public:
double func1(){...}
};
There's a push function that can cause the problem:
template<typename T>
void Stack::push(T element){
Base** pTemp= new Base*[elementNum+1];
for(unsigned i=0;i<elementNum;i++){
pTemp[i]=new Base;
*pTemp[i]=*array[i];
}
pTemp[elementNum]=new Base;
*pTemp[elementNum]=element;
delete[] array;
array=pTemp;
elementNum++;
return;
}
Upvotes: 1
Views: 1840
Reputation: 55395
There's a push function that can cause the problem
Spot on! You're slicing off the derived part of the objects located in the original array when assigning to the temporary array (if there ever were Derived
objects in the first place, you don't show the relevant code):
pTemp[i]=new Base; // creates a Base object
*pTemp[i]=*array[i]; // object slicing here, Derived part gets lost
Read about more about object slicing here.
If you wish to retain the dynamic type of the object, you need to copy pointers.
Upvotes: 2