Saturday, April 19, 2025

C++ OO Inheritance

Inheritance is a mechanism that allows a class (known as a derived class or subclass) to inherit the properties (data members and member functions) of another class (known as the base class or superclass).

When a derived class inherits from a base class, it automatically gets access to all the public and protected members of the base class. 

Inheritance is a key feature of object-oriented programming and allows for code reuse and the creation of hierarchies of classes that share common properties. 


#include <iostream>

using namespace std;

class Prim{
    public:
        string name;
        int age;

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

        void setAge(int y) {
            age = y;
        }
};

class Sec : public Prim {
    public:
        string job;

        void setJob(string z) {
            job = z;
        }

        void printAll() {
            cout << "Name: " << name << endl;
            cout << "Age: "  << age  << endl;
            cout << "Job: "  << job  << endl;
        }
};

int main() {

    Sec Object;
    Object.setName("Michael");
    Object.setAge(30);
    Object.setJob("Canceler");

    Object.printAll();

    return 0;
}

This C++ code defines two classes Prim and Sec where Sec is derived from Prim using inheritance.

The Prim class has two member variables, name and age and two member functions, setName() and setAge(), which are used to set the values of name and age, respectively.

The Sec class also has a member variable job and two member functions, setJob() and printAll().

The setJob() function is used to set the value of the job member variable. The printAll() function is used to print all the member variables of both Prim and Sec classes. In this function, the name and age member variables are inherited from the Prim class, whereas the job member variable is defined in the Sec class.

In the main() function, an object of Sec class is created, named Object. Then the setName(), setAge() and setJob() member functions are called to set the values of name, age and job, respectively.

Finally, the printAll() function is called to print all the member variables of the object Object.

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