It is generally not recommended to invoke a virtual method of a derived class from the constructor of the base class because the object may not be fully initialized yet. However, if it is necessary to do so, the following approach can be used:
this->virtual_method()
or Base::virtual_method()
.Example:
class Base {
public:
Base() {
this->initialize(); // Calls virtual method defined in derived class
}
virtual void initialize() {
// This method will be overridden in the derived class
}
};
class Derived : public Base {
public:
Derived() {}
void initialize() override {
// Code to initialize the derived class
}
};
Asked: 2023-06-06 00:41:59 +0000
Seen: 2 times
Last updated: Jun 06 '23