Skip to main content
Engineering LibreTexts

4.3: Implementing inheritance in C++

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    For creating a sub-class which is inherited from the base class we have to follow the below 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 
        int id_p; 
    // Sub class inheriting from Base Class(Parent) 
    class Child : public Parent 
        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; 


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

    Contributed by Harsh Agarwal
    Geeks for Geeks

    This page titled 4.3: Implementing inheritance in C++ is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?