I have a base class and two derived classes. The base class constructor should calculate some properties when it is called, although those properties depend on the derived class details. To avoid recoding the same steps inside each derived class constructor, I code these steps in the base class constructor like in the example below.
The problem is that when I do this, the base class constructor do not call the overridden methods. Instead, it calls its own method. Is there a way to solve that? Although it makes sense as well, what's the reason this behavior happens?
Coming from a C# background, that's very odd, since it would work nicely there. In C#, I would use the keyword base
to call any base class method whereas this
would always call the derived class methods.
Example:
example.h
#define _USE_MATH_DEFINES
#include <math.h>
class Base
{
public:
Base(void);
~Base(void);
protected:
virtual void Method(void);
};
class Derived : public Base
{
public:
Derived(void);
~Derived(void);
protected:
virtual void Method(void);
};
#include <iostream>
Base::Base()
{
this->Method(); // This calls Base->Method instead of Derived->Method
}
Base::~Base(){}
void Base::Method() // If I remove this, I have an error "externals undefined"
{
std::cout << "called Base->Method()" << endl;
}
Derived::Derived()
: Base()
{
this->Method(); // This obviously calls Derived->Method
}
Derived::~Derived(){}
void Derived::Method()
{
std::cout << "called Derived->Method()" << endl;
}
int main()
{
Base* d = new Derived();
/*
Outputs:
called Base->Method()
called Derived->Method()
*/
}
There is no way to do that, because when the base class constructor is run, the object is not yet an object of the derived type. In particular, data members introduced in the derived class are not initialised until after the base class constructor is run -- in essence, the base class object behaves like a data member of the derived class.
One way or another, you will have to defer the calculation until the derived class's constructor is entered. If I understand what you're trying to do correctly, the best way is probably to give the base class a member function that does the calculations and call that from the derived classes' constructors.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments