0

The output of this code yields "BASE!". Why hasn't the copy function of derived class been called in this example. They have the same signature and by my reasoning the derived one should be called. What is the problem?

#include <iostream>
using namespace std;

class Base{
   virtual void copy(const Base&b){
      cout<<"BASE!";
   }
public:
   Base()=default;
   Base(const Base&b){
      copy(b);
   }
};

class Derived: public Base{
    void copy(const Base&b) override{
        cout<<"DERIVED";
    }
};

int main() {
    Derived d;
    Derived b(d);
    return 0;
} 
  • You need to make copy method in Base – Jake Freeman Dec 15 '17 at 01:40
  • 3
    Possible duplicate of [Calling virtual functions inside constructors](https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors) – HolyBlackCat Dec 15 '17 at 01:42
  • Possible duplicate of [Invoking virtual function and pure-virtual function from a constructor](https://stackoverflow.com/questions/8642363/invoking-virtual-function-and-pure-virtual-function-from-a-constructor) – Brian Rodriguez Dec 15 '17 at 01:42

1 Answers1

4

It's not called because it doesn't exist yet.

The base class gets constructed first. Its copy-constructor calls the virtual method. The derived class does not get constructed until the base class gets constructed first, so the virtual class method, in the base class, is not overriden by anything.

Only when the derived class construction begins, does the virtual class method get overridden by the derived class.

The derived class instance simply does not exist until it actually gets constructed, and it doesn't get constructed until the base class is fully constructed, so the virtual method, during base class's construction, is not overridden by anything.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • That cleared things up, thanks! Is there a way to mitigate this problem, because it would be nice to let the derived class handle copying (for instance when creating derived classes of some containers) without unneeded code – Aleksa Ilić Dec 15 '17 at 01:45
  • 1
    The derived class needs to define the derived class's copy-constructor, and then call the base class's methods, or whatever needs to be done to recycle the code, efficiently. – Sam Varshavchik Dec 15 '17 at 01:46