Inheritance in cpp

Inheritance in cpp

One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class,
which makes it easier to create and maintain an application. This also provides
an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.

Defination Of Inheritance

Derive quality and characteristics from parents or ancestors. Like you inherit features of your parents.

Syntax

class subclass_name : access_mode base_class_name
{
  //body of subclass
};

Example

#include 
using namespace std;
 
//Base class
class Parent
{
    public:
      int id_p;
};
  
// Sub class inheriting from Base Class(Parent)
class Child : public Parent
{
    public:
      int id_c;
};
 
//main function
int main() 
   {
      
        Child obj1;
          
        // An object of class child has all data members
        // and member functions of class parent
        obj1.id_c = 7;
        obj1.id_p = 91;
        cout << "Child id is " <<  obj1.id_c << endl;
        cout << "Parent id is " <<  obj1.id_p << endl;
         
        return 0;
   } 

Output

Child id is 7
Parent id is 91



                    << PREVIEW >>



                    <<  NEXT   >>

Comments