C++ inheritance

This post shows through a simple example how inheritance works. Let’s consider a first class Parent with two member functions (fct1 and fct2). Note that fct2 is virtual. Let’s now consider a second class Child (which inherit from the class Parent) that also contain two member functions (fct1 and fct2). All this functions are protected, and they can be called from outside thanks to the public member functions callFunction1 and callFunction2 that belong to the class Parent. The question is : what will happen when these functions are called from the class Child ? In the case of fct1, which is not virtual, this is the function fct1 from the class Parent that is called. On the other hand, in the case of fct2, which is virtual, this is the function belonging to the class Child that is called. Note that the parent function can be called with the following syntax: Parent::fct2(). Note also that when calling the constructor of Child, the Parent constructor is called first.
The following program illustrates this explaination:

#include 


class Parent
{
public:
    Parent() {std::cout << "Constructor Parent" << std::endl;}

    void            callFunction1() { fct1(); }
    void            callFunction2() { fct2(); }

protected:
    void            fct1() 
    {   std::cout << "Class Parent :: function 1" << std::endl; }
    
    virtual void    fct2() 
    {   std::cout << "Class Parent :: function 2" << std::endl; }
};



class Child : public Parent
{
public:
    Child() {std::cout << "Constructor Child" << std::endl;}

protected:
    void            fct1() 
    {   std::cout << "Class Child :: function 1" << std::endl; }
    
    void            fct2() 
    {   std::cout << "Class Child :: function 2" << std::endl; 
        Parent::fct2(); }
};

int main()
{

    Child c;
    c.callFunction1();
    c.callFunction2();
    return 0;
}

This code output the following lines. The parent constructor is called before the child constructor. For fct1, this is the parent function called. For fct2, this is the child function called because the parent function is virtual.

Constructor Parent
Constructor Child
Class Parent :: function 1
Class Child :: function 2
Class Parent :: function 2

Leave a Reply

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