C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or modify
the attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no
need to define the member again. So less code is required in the class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
1. class derived_class_name :: visibility-mode base_class_name
2. {
3. // body of the derived class.
4. }
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
o When the base class is privately inherited by the derived class, public members of
the base class becomes the private members of the derived class. Therefore, the
public members of the base class are not accessible by the objects of the derived
class only by the member functions of the derived class.
o When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore, the
public members of the base class are accessible by the objects of the derived class
as well as by the member functions of the base class.
Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.
C++ Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from
the only one base class.
Where 'A' is the base class, and 'B' is the derived class.
C++ Single Level Inheritance Example: Inheriting Fields
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.
1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }
Output:
Salary: 60000
Bonus: 5000
C++ Single Level Inheritance Example: Inheriting
Methods
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }
Output:
Eating...
Barking...
Let's see a simple example.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }
Output:
Multiplication of a and b is : 20
In the above example, class A is privately inherited. Therefore, the mul() function of class
'A' cannot be accessed by the object of class B. It can only be accessed by the member
function of class B.
How to make a Private Member Inheritable
The private member is not inheritable. If we modify the visibility mode by making it public,
but this takes away the advantage of data hiding.
C++ introduces a third visibility modifier, i.e., protected. The member which is declared
as protected will be accessible to all the member functions within the class as well as the
class immediately derived from it.
Visibility modes can be classified into three categories:
o Public: When the member is declared as public, it is accessible to all the functions
of the program.
o Private: When the member is declared as private, it is accessible within the class
only.
o Protected: When the member is declared as protected, it is accessible within its
own class as well as the class immediately derived from it.
Visibility of Inherited Members
Base class visibility Derived class visibility
Public Private Protected
Private Not Inherited Not Inherited Not Inherited
Protected Protected Private Protected
Public Public Private Protected
C++ Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.
C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived class
acquires all the members of all its base classes.
Let's see the example of multi level inheritance in C++.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }
Output:
Eating...
Barking...
Weeping...
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.
Syntax of the Derived class:
1. class D : visibility B-1, visibility B-2, ?
2. {
3. // Body of the class;
4. }
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
C++ Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14. class B : public A
15. {
16. protected:
17. int b;
18. public:
19. void get_b()
20. {
21. std::cout << "Enter the value of 'b' : " << std::endl;
22. cin>>b;
23. }
24. };
25. class C
26. {
27. protected:
28. int c;
29. public:
30. void get_c()
31. {
32. std::cout << "Enter the value of c is : " << std::endl;
33. cin>>c;
34. } };
35. class D : public B, public C
36. {
37. protected:
38. int d;
39. public:
40. void mul()
41. {
42. get_a();
43. get_b();
44. get_c();
45. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
46. }
47. };
48. int main()
49. {
50. D d;
51. d.mul();
52. return 0;
53. }
Output:
Enter the value of 'a' :
10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000
C++ Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from a
base class.
Syntax of Hierarchical inheritance:
1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }
1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::endl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }
Output:
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.
The symbol of an address is represented by a pointer. In addition to creating and
modifying dynamic data structures, they allow programs to emulate call-by-reference.
One of the principal applications of pointers is iterating through the components of arrays
or other data structures. The pointer variable that refers to the same data type as the
variable you're dealing with has the address of that variable set to it (such as an int or
string).
Syntax
1. datatype *var_name;
2. int *ptr; // ptr can point to an address which holds int data
How to use a pointer?
1. Establish a pointer variable.
2. employing the unary operator (&), which yields the address of the variable, to
assign a pointer to a variable's address.
3. Using the unary operator (*), which gives the variable's value at the address
provided by its argument, one can access the value stored in an address.
Since the data type knows how many bytes the information is held in, we associate it with
a reference. The size of the data type to which a pointer points is added when we
increment a pointer.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees etc. and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions and structures. It reduces the
code and improves the performance.
Symbols used in pointer
Symbol Name Description
& (ampersand sign) Address operator Determine the address of a variable.
∗ (asterisk sign) Indirection operator Access the value of an address.
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
1. int ∗ a; //pointer to int
2. char ∗ c; //pointer to char
Pointer Example
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int number=30;
6. int ∗ p;
7. p=&number;//stores the address of number variable
8. cout<<"Address of number variable is:"<<&number<<endl;
9. cout<<"Address of p variable is:"<<p<<endl;
10. cout<<"Value of p variable is:"<<*p<<endl;
11. return 0;
12. }
Output:
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Pointer Program to swap 2 numbers without using 3rd
variable
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=20,b=10,∗p1=&a,∗p2=&b;
6. cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
7. ∗p1=∗p1+∗p2;
8. ∗p2=∗p1-∗p2;
9. ∗p1=∗p1-∗p2;
10. cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
11. return 0;
12. }
Output:
Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20
What are Pointer and string literals?
String literals are arrays of character sequences with null ends. The elements of a string
literal are arrays of type const char (because characters in a string cannot be modified)
plus a terminating null-character.
What is a invalid pointer?
A pointer must point to a valid address, not necessarily to useful items (like for arrays).
We refer to these as incorrect pointers. Additionally, incorrect pointers are uninitialized
pointers.
1. int *ptr1;
2. int arr[10];
3. int *ptr2 = arr+20;
Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of the bounds of arr,
making it likewise weak. (Take note that not all build failures are caused by faulty
references.)
What is a null pointer?
A null pointer is not merely an incorrect address; it also points nowhere. Here are two
ways to mark a pointer as NULL:
1. int *ptr1 = 0;
2. int *ptr2 = NULL;
What is a pointer to a pointer?
In C++, we have the ability to build a pointer to another pointer, which might then point
to data or another pointer. The unary operator (*) is all that is needed in the syntax for
declaring the pointer for each level of indirection.
1. char a;
2. char *b;
3. char ** c;
4. a = 'g';
5. b = &a;
6. c = &b;
Here b points to a char that stores 'g', and c points to the pointer b.
What are references and pointers?
1. Call-By-Value
2. Call-By-Reference with a Pointer Argument
3. Call-By-Reference with a Reference Argument
Example
1. #include
2. using namespace std;
3. // Pass-by-Value
4. int square1(int n)
5. {cout << "address of n1 in square1(): " << &n << "\n";
6. n *= n;
7. return n;
8. }
9. // Pass-by-Reference with Pointer Arguments
10. void square2(int* n)
11. {
12. cout << "address of n2 in square2(): " << n << "\n";
13. *n *= *n;
14. }
15. // Pass-by-Reference with Reference Arguments
16. void square3(int& n)
17. {
18.
19. cout << "address of n3 in square3(): " << &n << "\n";
20. n *= n;
21. }
22. void example()
23. {
24. // Call-by-Value
25. int n1 = 8;
26. cout << "address of n1 in main(): " << &n1 << "\n";
27. cout << "Square of n1: " << square1(n1) << "\n";
28. cout << "No change in n1: " << n1 << "\n";
29.
30. // Call-by-Reference with Pointer Arguments
31. int n2 = 8;
32. cout << "address of n2 in main(): " << &n2 << "\n";
33. square2(&n2);
34. cout << "Square of n2: " << n2 << "\n";
35. cout << "Change reflected in n2: " << n2 << "\n";
36.
37. // Call-by-Reference with Reference Arguments
38. int n3 = 8;
39. cout << "address of n3 in main(): " << &n3 << "\n";
40. square3(n3);
41. cout << "Square of n3: " << n3 << "\n";
42. cout << "Change reflected in n3: " << n3 << "\n";
43. }
44. // Driver program
45. int main() { example(); }
Output
Pointer to object
Pointer to object in c++ is defined as the pointer that is used for accessing objects.
A pointer is a variable that stores the memory address of another variable.
The types of the pointer are Null pointer, Void pointer, Wild pointer, and Dangling
pointer.
#include<iostream>
class Complex{
int real, imaginary;
public:
void getData(){
cout<<"The real part is "<< real<<endl;
cout<<"The imaginary part is "<< imaginary<<endl;
void setData(int a, int b){
real = a;
imaginary = b;
};
int main(){
Complex *ptr = new Complex;
(*ptr).setData(1, 54); is exactly same as
(*ptr).getData(); is as good as
return 0;
The output of the following program is shown below,
C++ this Pointer
In C++ programming, this is a keyword that refers to the current instance of the class.
There can be 3 main usage of this keyword in C++.
o It can be used to pass current object as a parameter to another method.
o It can be used to refer current class instance variable.
o It can be used to declare indexers.
C++ this Pointer Example
Let's see the example of this keyword in C++ that refers to the fields of current class.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id; //data member (also instance variable)
6. string name; //data member(also instance variable)
7. float salary;
8. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
101 Sonoo 890000
102 Nakul 59000
C++ virtual function
o A C++ virtual function is a member function in the base class that you redefine in
a derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the
function.
o There is a necessity to use the single pointer to refer to all the objects of the
different classes. So, we create the pointer to the base class that refers to all the
derived objects. But, when base class pointer contains the address of the derived
class object, always executes the base class function. This issue can only be resolved
by using the 'virtual' function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be invoked
at the runtime based on the type of the object pointed by the base class pointer.
Late binding or Dynamic linkage
In late binding function call is resolved during runtime. Therefore compiler determines
the type of object at runtime, and then binds the function call.
Rules of Virtual Function
o Virtual functions must be members of some class.
o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes
must be identical. If the two functions with the same name but different prototypes,
C++ will consider them as the overloaded functions.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
9. std::cout << "Value of x is : " << x<<std::endl;
10. }
11. };
12. class B: public A
13. {
14. int y = 10;
15. public:
16. void display()
17. {
18. std::cout << "Value of y is : " <<y<< std::endl;
19. }
20. };
21. int main()
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }
Output:
Value of x is : 5
In the above example, * a is the base class pointer. The pointer can only access the base
class members but not the members of the derived class. Although C++ permits the base
pointer to point to any object derived from the base class, it cannot directly access the
members of the derived class. Therefore, there is a need for virtual function which allows
the base pointer to access the members of the derived class.
C++ virtual function Example
Let's see the simple example of C++ virtual function used to invoked the derived class in
a program.
1. #include <iostream>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }
Output:
Derived Class is invoked
Pure Virtual Function
o A virtual function is not used for performing any task. It only serves as a
placeholder.
o When the function has no definition, such function is known as "do-nothing"
function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative to
the base class.
o A class containing the pure virtual function cannot be used to declare the objects
of its own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.
Pure virtual function can be defined as:
1. virtual void display() = 0;
Let's see a simple example:
1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base class." << std::endl;
14. }
15. };
16. int main()
17. {
18. Base *bptr;
19. //Base b;
20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24. }
Output:
Derived class is derived from the base class.
In the above example, the base class contains the pure virtual function. Therefore, the
base class is an abstract base class. We cannot create the object of the base class.