Skip to main content
Engineering LibreTexts

4.3: Implementing inheritance in C++

  • Page ID
    34660
  • For creating a sub-class which is inherited from the base class we have to follow the below syntax.
    Syntax:

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

    Here, subclass_name is the name of the sub class, access_mode is the mode in which you want to inherit this sub class for example: public, private etc. and base_class_name is the name of the base class from which you want to inherit the sub class.
    Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.

    
    // C++ program to demonstrate implementation 
    // of Inheritance 
    
    #include <bits/stdc++.h> 
    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
    

    In the above program the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data members of the class ‘Parent’ will also be inherited by the class ‘Child’.

    by-sa.png
    Contributed by Harsh Agarwal
    Geeks for Geeks