1

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;
}
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
balazs94
  • 11
  • 3
  • Not enough information. Please, we need a short compilable example that reproduces your problem ([SSCCE](http://sscce.org)). – jrok Apr 27 '14 at 12:09
  • You seem to have two implementations of `double Base::func()`. – celtschk Apr 27 '14 at 12:09
  • It looks like you are having two definitions of `Base::func()` -- one inline in the class, and a second outside? I suggest you post more context and/or a small working example showing the issue, as this surely is not right. – Soren Apr 27 '14 at 12:10
  • @Soren I suppose it's just a typo. Compiler will emit an error for that. – Adriano Repetti Apr 27 '14 at 12:13
  • sorry, new to this forum, there are 2 different functions – balazs94 Apr 27 '14 at 12:17
  • ... I don't see any code which creates any object of the type `Derived` (only see code creating `Base`) -- why do you expect the method of `Derived` should be called? – Soren Apr 27 '14 at 12:21

1 Answers1

2

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.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141