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:

  1. Include Libraries: Include the necessary header file (iostream) for input-output operations.

  2. Base Class Definition: Define a base class Base with a constructor that calls the method().

  3. Base Class Method Definition: Define a virtual method method() in the Base class that prints "Base::method() called" to the console.

  4. Derived Class Definition: Define a derived class Derived that publicly inherits from the Base class.

  5. Override Method in Derived Class: Define the method() in the Derived class, overriding the base class method. This method prints "Derived::method() called" to the console.

  6. Main Function: In the main() function, create an instance of the Derived class (Derived d;). When this object is created, it calls the constructor of the Base class due to inheritance.

  7. Constructor Execution: As the Derived object is created, it invokes the Base class constructor.

  8. Virtual Method Invocation: Inside the Base constructor, the method() is called. Since the method() is virtual and overridden in the Derived class, polymorphism ensures that the overridden method in the Derived class is executed.

  9. 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.