Saturday, April 19, 2025

C++ OO Private Inheritance

Private inheritance is one of the three types of inheritance that allows a derived class to inherit the properties of a base class. With private inheritance, all public and protected members of the base class become private members of the derived class. This means that the derived class can access the inherited members, but they are not visible to any external code. 

#include <iostream>

using namespace std;

class Prim{
    protected:
        string name;

    public:
        void setName(string x) {
            name = x;
        }
};

class Sec : private Prim{
    public:
        void printName() {
            cout << "Name from Prim Cls: " << name << endl;
        }

        void caller(string x) {
            setName(x);
        }
};

int main() {

    Sec Object;
    Object.caller("Anabela");
    Object.printName();

    return 0;
}

The class Sec inherits from the class Prim using private inheritance. This means that Sec is a derived class of Prim, but it can only access the protected and public members of Prim through its own interface.

In other words, Sec can access the setName function of Prim, which is public, and can set the value of name, which is protected. However, it cannot access name directly, as it is private in Sec.

The printName function in Sec is able to print the value of name by calling it through the setName function which is public in Prim.

In the main function, an object of Sec is created and the caller function is called to set the value of name to "Anabela". The printName function is then called to print the value of name, which is "Anabela" in this case.

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