Saturday, April 19, 2025

C++ OO Constructor Calling Constructor

Constructor calling constructor is useful when a derived class needs to initialize its base class members before initializing its own members. In some cases, it can make the code more concise and easier to read. 


#include <iostream>

using namespace std;

class Prim{
    public:
        string name;

        Prim(string x) {
            name = x;
        }
};

class Sec : public Prim{
    public:
        Sec(string y) : Prim(y) {
            cout << "Done" << endl;
        }

        void printAll() {
            cout << name << endl;
        }
};

int main() {

    Sec Obj("Michael");
    Obj.printAll();

    return 0;
}

A constructor in C++ can call another constructor using a technique called constructor chaining or constructor delegation.

In the code you provided, the constructor of the Sec class is calling the constructor of the Prim class using the syntax : Prim(y) in the constructor initialization list. This means that before executing the body of the Sec constructor, the constructor of the Prim class is called first with the argument y. This initializes the name member variable of the Prim class with the value of y.

Then, the body of the Sec constructor executes, which simply outputs "Done" to the console. Finally, the printAll() function is called on the Obj object, which prints the value of the name member variable inherited from the Prim class.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...