Maybe this was covered in some other topic. But I did not find any satisfactory answer. Could somebody explain me following. I have following code:
#include <iostream>
class Base {
public:
Base() {
foo();
}
virtual void foo() {
std::cout << "Base::foo()" << std::endl;
}
};
class Derived : public Base {
public:
Derived(): Base() {}
virtual void foo() {
std::cout << "Derived::foo()" << std::endl;
}
};
int main() {
Derived* p = new Derived();
}
Now my question is why does the Base creator calls foo method which is in the Base and not in the Derived class, although it is overridden in the Derived class?
It is bad pratice to call virtual functions inside of constructor. I just give simple example, which will show disadvantages of this approach (Note: It is about c++ (other languages can use different implementation).
Order of calling constructors in your code is:
1) Base
2) Derived
At the moment of calling Base constructor, member specified in Derived class is not created. Suppose, you can use function, overrided in Derived class. In this case you can invoke functions, which will have access to NOT CREATED DATA (note, at the moment Derived class is not created). Obviously, it is too dangerous. At that point it seems logicaly to call function, which can work with created data (in this case it is data of Base class)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments