ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

C++ Inheritance

prodevelopertutorial February 25, 2020

In. this tutorial we shall learn about below topics:

  1. Introduction
  2. Deriving by different access specifiers:
  3. C++ Base class Pointer and Derived class pointer.
  4. Virtual Base Class
  5. Constructor and Destructor calls in Inheritance
  6. Constructor and Destructor calls in Multiple Inheritance
  7. Pointers and Inheritance

 

1. Introduction

 

Inheritance is a way of creating new class with the help of existing class.

The existing class is called as base class [parent class, super class], new class is called as inherited class [child class, sub class, derived class].

The new derived class can have it’s own data members and member functions along with some of the data members and member functions of the base class.

Syntax:

class <DerivedCalssName> : <accessSpecifier> <BaseClassName>

 

The size of the derived class will always be equall to or greater then base class.

Derived class can only access the public or protected members of the base class. Private data members will be inherited but cannot be used.

 

Example:

#include<iostream>

using namespace std;




class A

{

            int a;

            public:

            void display()

            {

            cout<<"This is display from A class"<<endl;

            }

};







class B :public A

{

            int b;

            public:

            void display()

            {

            cout<<"This is display from B class"<<endl;

            }




};




int main()

{

A a1;

a1.display(); // "A" class display()



B b1;

b1.display(); // "B" class display function.


cout<<"Size of object of A class " << sizeof(a1)<<endl;

cout<<"Size of object of B class " << sizeof(b1)<<endl;


}

Output:

This is display from A class

This is display from B class

Size of object of A class 4

Size of object of B class 8

 

 

2. Deriving by different access specifiers:

 

There are 3 types of access specifiers that can be used to derive.

  1. public
  2. private
  3. protected

 

Deriving using public access specifier:

  1. Public members of base class will be public members of derived class.
  2. Protected members of base class will be protected members of derived class.
  3. Private members of the base class are not accessable to derived class. Hence are not inherited.

 

Example:

class DerivedClass : public BaseClass

 

Deriving using protected access specifier:

  1. Public members of base class will be protected members of derived class.
  2. Protected members of base class will be protected members of derived class.
  3. Private members of the base class are not accessable to derived class. Hence are not inherited.

 

Example:

class DerivedClass : protected BaseClass

Deriving using private access specifier:

  1. Public members of base class will be private members of derived class.
  2. Protected members of base class will be private members of derived class.
  3. Private members of the base class are not accessable to derived class. Hence are not inherited.

 

Example:

class DerivedClass : private BaseClass

 

3. C++ Base class Pointer and Derived class pointer.

 

Base class pointer:

 

The base class pointer can store the address of a derived class. This is valid because, the derived class object will he having the members of the base class.

Hence when the pointer of base class can access it’s members. However, in this situation, the pointer will not be able to access derived class members. As the base class pointer will not be having any information about the members of derived class.

 

Example:

#include<iostream>

using namespace std;

class Base

{

            public:

            int a;

            void display()

            {

              cout<<"This is base class show()"<<endl;

            }

};

class Derived : public Base

{

            public:

            int b;

            void display()

            {
              cout<<"This is derived class show()"<<endl;

            }

};


int main()

{


Base *b1;

Derived der;


b1 = &der;

b1->display();

b1->a;

// b1->b; // error member b is not found in Base class

return 0;

}


Output:

This is base class show()

 

Derived Class Pointer:

 

The derived class pointer cannot hold the address of base class object. Because, the derived class pointer is supposed to access all the members of both base class and derived class.

By making derived class pointer to hold the address of base class, it cannot access the derived class members. Hence the compiler will throw an error.

 

Example:

same as above program, we do a slight change in main()

int main()

{

            Base b1;

            Derived *der;

            der= &b1; //error

}


4. Virtual Base Class

 

Before going to “virtual base class”, we shall look why we need this. We shall cover types of inheritance in next chapter, but for now, there is a concept of multipath inheritance.

multiparty inheritance

From the above example we can see that, Class B is inheriting Class A, Class C is also inheriting Class A. And Class D is inheriting both B and C. Hence here Class A will be inherited twice. Hence when we try to access Class A variable we get the below error:

 

error: non-static member 'a' found in multiple base-class subobjects of type 'A':

    class D -> class B -> class A

    class D -> class C -> class A

                        cout<<"The value of a "<<a;

                                                 ^

note: member found by ambiguous name lookup

                int a;
                    ^

 

1 error generated.

 

To make the compiler to inherit only once, we should make base class as “virtual” when ever it is being  inherited. By making a Class virtual, compiler will take necessary steps to make sure that all the classes are inherited only once.

 

“virtual” is the keyword used to declare a virtual class.

/*

* File     : virtual_base_class.cpp

* Author   : ajay.thousand@gmail.com

* Copyright: @ prodevelopertutorial.com

*/

#include<iostream>
using namespace std;




class A

{
            public:
                       int a;

};




class B: virtual public A
{
            public:
                        int b;

};




class C: virtual public A
{
            public:
                        int c;

};




class D: public B, C
{

            public:
                        int d;

                        void display()

                        {

                                    cout<<"The value of a "<<a;

                        }

};


int main()

{

            D d1;

}


When you compile the above code, no error will be shown.

 

5. Constructor and Destructor calls in Inheritance

During inheritance, always the base class constructor will be called, and later derived class constructor will be called.

 

Similarly, the destructor call will be in reverse. First derived class destructor will be called, then the base class destructor will be called.

 

Example:

 

/*

* File     : constructor_destructor_in_inheritance.cpp

* Author   : ajay.thousand@gmail.com

* Copyright: @ prodevelopertutorial.com

*/




#include<iostream>
using namespace std;




class A

{

            public:

                        A()

                        {

                                    cout<<"Constructor of A"<<endl;

                        }

                        ~A()

                        {

                                    cout<<"Destructor of A"<<endl;

                        }

};




class B: public A

{

            public:

                        B()

                        {

                                    cout<<"Constructor of B"<<endl;

                        }

                        ~B()

                        {

                                    cout<<"Destructor of B"<<endl;

                        }

};




class C: public B

{

            public:

                        C()

                        {

                                    cout<<"Constructor of C"<<endl;

                        }

                        ~C()

                        {

                                    cout<<"Destructor of C"<<endl;

                        }

};




class D: public C

{

            public:

                        D()

                        {

                                    cout<<"Constructor of D"<<endl;

                        }

                        ~D()

                        {

                                    cout<<"Destructor of D"<<endl;

                        }

};




int main()

{

            D d1;

}


 

Output:

 

Constructor of A

Constructor of B

Constructor of C

Constructor of D

Destructor of D

Destructor of C

Destructor of B

Destructor of A

 

6. Constructor and Destructor calls in Inheritance example

 

If a class is having multiple inheritance, then the constructor call will be according to the order of sequence.

 

Example:

 

/*

* File     : constructor_destructor_in_inheritance.cpp

* Author   : ajay.thousand@gmail.com

* Copyright: @ prodevelopertutorial.com

*/




#include<iostream>




using namespace std;




class A

{

            public:

                        A()

                        {

                                    cout<<"Constructor of A"<<endl;

                        }

                        ~A()

                        {

                                    cout<<"Destructor of A"<<endl;

                        }

};




class B

{

            public:

                        B()

                        {

                                    cout<<"Constructor of B"<<endl;

                        }

                        ~B()

                        {

                                    cout<<"Destructor of B"<<endl;

                        }

};




class C: public B, A

{

            public:

                        C()

                        {

                                    cout<<"Constructor of C"<<endl;

                        }

                        ~C()

                        {

                                    cout<<"Destructor of C"<<endl;

                        }

};

int main()

{

            C c1;

}

 

Constructor of B

Constructor of A

Constructor of C

Destructor of C

Destructor of A

Destructor of B

 

7. Pointers and Inheritance

In C++ private data members and public data members are stored in successive memory locations. Hence a pointer to public data member will give access to the private data member also.

 

Same holds true for derived class.

 

As we are storing the data in stack, the base class variable will be stored first and derived class variable will be stored next. Hence we get the address of derived class data member then using that pointer we access base private class data member. As shown in the example below:

 

/*

* File     : pointers_inheritance.cpp

* Author   : ajay.thousand@gmail.com

* Copyright: @ prodevelopertutorial.com

*/




#include<iostream>




using namespace std;

class A

{

private:

            int a;




public:

            A()

            {

                        a = 10;

            }




};




class B : public A

{




public:

            int b;




            B()

            {

                        b = 20;

            }




};




int main()

{

            B b1;




//pointer to the derived class data member

            int *ptr = &b1.b;




            cout<<"The value of variable b is "<< *(ptr)<<endl;

           

//access the base class private variable

            ptr --;




            cout<<"The value of variable a is "<< *(ptr)<<endl;







}

Output:

The value of variable b is 20

The value of variable a is 10
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT