1

I thought that if I create a base class that has a constructor which calls a virtual method, that if a child class overrode that method, it would be called instead.

Consider

#include <iostream>

using namespace std;

class Base {
    protected:
    void CreateA();
    virtual void CreateB();
    public:
    Base();
    ~Base();
};
Base::Base(){this->CreateA();}
Base::~Base(){}
void Base::CreateA(){cout << "BASE CREATE A " << endl; this->CreateB();}
void Base::CreateB(){cout << "BASE CREATE B " << endl;}

class Child : public Base {
    protected:
    virtual void CreateB();
    public:
    Child();
    ~Child();
};
Child::Child(){}
Child::~Child(){}
void Child::CreateB(){cout << "Child CREATE B " << endl;}

int main()
{
    Child child;

    return 0;
}

This would print out

BASE CREATE A

BASE CREATE B

and not

BASE CREATE A

CHILD CREATE B

as I would have expected.

How can I make this so?

Community
  • 1
  • 1
ICU_
  • 159
  • 1
  • 8

0 Answers0