c++ call overriden method from constructor
#include <iostream>
class Base {
public:
Base() {
method();
}
virtual void method() {
std::cout << "Base::method() called" << std::endl;
}
};
class Derived : public Base {
public:
void method() override {
std::cout << "Derived::method() called" << std::endl;
}
};
int main() {
Derived d;
return 0;
}
Explanation of steps:
Include Libraries: Include the necessary header file (
iostream
) for input-output operations.Base Class Definition: Define a base class
Base
with a constructor that calls themethod()
.Base Class Method Definition: Define a virtual method
method()
in theBase
class that prints"Base::method() called"
to the console.Derived Class Definition: Define a derived class
Derived
that publicly inherits from theBase
class.Override Method in Derived Class: Define the
method()
in theDerived
class, overriding the base class method. This method prints"Derived::method() called"
to the console.Main Function: In the
main()
function, create an instance of theDerived
class (Derived d;
). When this object is created, it calls the constructor of theBase
class due to inheritance.Constructor Execution: As the
Derived
object is created, it invokes theBase
class constructor.Virtual Method Invocation: Inside the
Base
constructor, themethod()
is called. Since themethod()
is virtual and overridden in theDerived
class, polymorphism ensures that the overridden method in theDerived
class is executed.Output: The output of this program will be:
Derived::method() called
This output demonstrates that even though the method()
is called from the constructor of the Base
class, the overridden version of the method in the Derived
class is executed due to polymorphic behavior.