This post explains Simple inheritance program in C++. In C++, inheritance is a mechanism that allows a class (known as the derived class) to inherit the properties and methods of another class (known as the base class). This allows for code reuse and a more organized and efficient way to create new classes. The derived class can also have its own properties and methods, in addition to those inherited from the base class.

In C++, inheritance is implemented using the “:” operator. The derived class is defined by specifying the base class after the “:” operator, like this: “class DerivedClass : public BaseClass”. The keyword “public” is used to specify the access level of the inheritance, which determines what members of the base class are accessible to the derived class.

In the example above, the class “Parent” is the base class, and the class “Child” is the derived class. The Child class inherits the public properties and methods of the Parent class, including the x variable and the setX and getX methods. The Child class also has its own y variable and setY and getY methods, which are not inherited from the Parent class.

By using inheritance, we can create a new class that has all the properties and methods of an existing class and we can also add new properties and methods to it. It helps to reduce the code redundancy and makes it easy to maintain the code.


Simple inheritance program in C++:

#include <iostream>

class Parent {
   public:
      int x;
      void setX(int x) { this->x = x; }
      int getX() { return x; }
};

class Child : public Parent {
   public:
      int y;
      void setY(int y) { this->y = y; }
      int getY() { return y; }
};

int main() {
   Child c;
   c.setX(10);
   c.setY(20);
   std::cout << "x = " << c.getX() << ", y = " << c.getY() << std::endl;
   return 0;
}

In this program, the Child class inherits from the Parent class using the “: public Parent” syntax. This means that the Child class has access to all of the public members of the Parent class, in this case the x variable and the setX and getX methods. The Child class also has its own y variable and setY and getY methods.

In the main function, an instance of the Child class is created, and the setX and setY methods are used to set the values of the x and y variables. The getX and getY methods are then used to retrieve the values and print them out.

You can also achieve the same thing in C, however the syntax is a bit different and the class structure is not built-in in C, so you need to use structs and function pointers.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.