0% found this document useful (0 votes)
28 views

Inheritance

Inheritance

Uploaded by

Soumyo Sarkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Inheritance

Inheritance

Uploaded by

Soumyo Sarkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Object Oriented Programming

Inheritance: Derived and base classes, Class hierarchies, public, private, and protected derivations, constructors in derived
classes, destructors in derived classes, constructors invocation and data members initialization in derived classes, classes
within classes, virtual base class.

Inheritance in C++ is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an
important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods
and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Terms used in Inheritance


Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are
created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or
child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or
a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of c++ Inheritance

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning
of "extends" is to increase the functionality.

Need of Java Inheritance


Code Reusability: The basic need of an inheritance is to reuse the features. If you have defined some functionality once,
by using the inheritance you can easily use them in other classes and packages.

Extensibility: The inheritance helps to extend the functionalities of a class. If you have a base class with some
functionalities, you can extend them by using the inheritance in the derived class.
Implantation of Method Overriding: Inheritance is required to achieve one of the concepts of Polymorphism which is
Method overriding.

Achieving Abstraction: Another concept of OOPs that is abstraction also needs inheritance.

Modes of Inheritance: There are 3 modes of inheritance.

Public Mode: If we derive a subclass from a public base class. Then the public member of the base class will become public
in the derived class and protected members of the base class will become protected in the derived class.

Protected Mode: If we derive a subclass from a Protected base class. Then both public members and protected members
of the base class will become protected in the derived class.

Private Mode: If we derive a subclass from a Private base class. Then both public members and protected members of the
base class will become Private in the derived class.

Types of Inheritance:-

 Single inheritance
 Multilevel inheritance
 Multiple inheritance
 Hierarchical inheritance
 Hybrid inheritance

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one subclass is inherited by one base class only.
Example
#include<iostream>
using namespace std;
class Vehicle { // base class
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
class Car : public Vehicle { // sub class derived from a single base classes

};

int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

Output
This is a Vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from more than one class.
i.e one subclass is inherited from more than one base class.
Example:
// multiple inheritance
#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 wheeler Vehicle
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another derived class.

// C++ program to implement


// Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {

public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is inherited from a single base class.
i.e. more than one derived class is created from a single base class.

// C++ program to implement


// Hierarchical Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritances:

// C++ program for Hybrid Inheritance

#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};
// first sub class
class Car : public Vehicle {
};
// second sub class
class Bus : public Vehicle, public Fare {
};
// main function
int main()
{
Bus obj2;
return 0;
}

Output
This is a Vehicle
Fare of Vehicle

Difference between Single Inheritance and Multiple Inheritance

S.NO Single Inheritance Multiple Inheritance

Single inheritance is one in which Whereas multiple inheritance is one in which


the derived class inherits the single the derived class acquires two or more base
1. base class. classes.
S.NO Single Inheritance Multiple Inheritance

In single inheritance, the derived While in multiple inheritance, the derived class
class uses the features of the single uses the joint features of the inherited base
2. base class. classes.

Single inheritance requires a small While multiple inheritance requires more run
run time as compared to multiple time as compared to single inheritance due to
3. inheritance due to less overhead. more overhead.

Single inheritance is a lot close to In contrast, multiple inheritance is a lot close to


4. specialization. generalization.

Multiple inheritance is implemented as


Single inheritance is implemented as
Class DerivedClass_name :
Class DerivedClass_name :
access_specifier Base_Class1,
access_specifier Base_Class{};
5. access_specifier Base_Class2, ….{};
.
.

Single inheritance is simple in While multiple inheritance is complex in


6. comparison to multiple inheritance. comparison to single inheritance.

C++ supports multiple inheritance but multiple


Single inheritance can be
inheritance can’t be implemented in any
implemented in any programming
programming language(C#, Java doesn’t
language.
7. support multiple inheritance).

Single inheritance constructs an Multiple inheritance constructs Inheritance


8. inheritance tree. Directed Acyclic Graph (DAG).

The below table summarizes the above three modes and shows the access specified of the members of the base class in the
subclass when derived in public, protected and private modes:
Constructors in Derived Class in C++
In C++, constructors in derived classes are special member functions used to initialize objects of derived classes. When you
create an object of a derived class, its constructor is called to initialize both the base class part and the derived class part
of the object. Constructors in derived classes can call constructors of their base classes explicitly to ensure proper
initialization of the inherited members.

Example:
#include <iostream>
// Base class
class Base {
public:
Base() {
std::cout << "Base constructor\n";
}
};
// Derived class
class Derived : public Base {
public:
Derived() {
std::cout << "Derived constructor\n";
}
};
int main() {
Derived d; // Creating an object of the derived class
return 0;
}
Let's break it down:
In this example, when you create an object of the Derived class (Derived d;), its constructor is called. The constructor of
the Derived class implicitly calls the constructor of the Base class (Base ()), ensuring that both the base class and the
derived class are properly initialized.
Destructors in Derived Class in C++
In C++, destructors in derived classes play a crucial role in ensuring proper cleanup of resources allocated by both the base
class and the derived class. A destructor in C++ is a special member function of a class that is automatically called when an
object of that class goes out of scope or is explicitly deleted. In the context of derived classes, a derived class can have its
own destructor in addition to the destructor of its base class.

Example:
#include <iostream>
class Base {
public:
Base() {
std::cout << "Base constructor called" << std::endl;
}

~Base() {
std::cout << "Base destructor called" << std::endl;
}
};

class Derived : public Base {


public:
Derived() {
std::cout << "Derived constructor called" << std::endl;
}

~Derived() {
std::cout << "Derived destructor called" << std::endl;
}
};

int main() {
Derived derivedObj;
return 0;
}

Let's break it down:


In this example, when the derivedObj goes out of scope at the end of the main() function, the destructors are called in the
following order:
1. Derived destructor
2. Base destructor

Order of Constructor/ Destructor Call in C++


Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the
members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of
the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the
order of invocation is that the base class’s default constructor will be invoked first and then the derived class’s default
constructor will be invoked.

Why the base class’s constructor is called on creating an object of derived class?
To understand this you will have to recall your knowledge on inheritance. What happens when a class is inherited from
other? The data members and member functions of base class comes automatically in derived class based on the access
specified but the definition of these members exists in base class only. So when we create an object of derived class, all of
the members of derived class must be initialized but the inherited members in derived class can only be initialized by the
base class’s constructor as the definition of these members exists in base class only. This is why the constructor of base
class is called first to initialize all the inherited members.

// C++ program to show the order of constructor call


// in single inheritance

#include <iostream>
using namespace std;

// base class
class Parent
{
public:

// base class constructor


Parent()
{
cout << "Inside base class" << endl;
}
};

// sub class
class Child : public Parent
{
public:

//sub class constructor


Child()
{
cout << "Inside sub class" << endl;
}
};

// main function
int main() {

// creating object of sub class


Child obj;

return 0;
}
Output:
Inside base class
Inside sub class

Order of constructor call for Multiple Inheritance


For multiple inheritance order of constructor call is, the base class’s constructors are called in the order of inheritance and
then the derived class’s constructor.

#include <iostream>
using namespace std;
// first base class
class Parent1
{
public:
// first base class's Constructor
Parent1()
{
cout << "Inside first base class" << endl;
}
};
// second base class
class Parent2
{
public:

// second base class's Constructor


Parent2()
{
cout << "Inside second base class" << endl;
}
};

// child class inherits Parent1 and Parent2


class Child : public Parent1, public Parent2
{
public:
// child class's Constructor
Child()
{
cout << "Inside child class" << endl;
}
};
int main() {

// creating object of class Child


Child obj1;
return 0;
}

Output:
Inside first base class
Inside second base class
Inside child class
Order of constructor and Destructor call for a given order of Inheritance

Classes within classes: A nested class is a class which is declared in another enclosing class. A nested class is a member
and as such has the same access rights as any other member. The members of an enclosing class have no special access to
members of a nested class; the usual access rules shall be obeyed.

Example
#include<iostream>

using namespace std;

class A {

public:

class B {

private:

int num;

public:

void getdata(int n) {

num = n;

void putdata() {

cout<<"The number is "<<num;

};

};

int main() {

cout<<"Nested classes in C++"<< endl;

A :: B obj;

obj.getdata(9);

obj.putdata();

return 0;

Output
Nested classes in C++
The number is 9

Virtual base class in C++


Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class
appearing in an inheritance hierarchy when using multiple inheritances.
Need for Virtual Base Classes: Consider the situation where we have one class A. This class A is inherited by two
other classes B and C. Both these class are inherited into another in a new class D as shown in figure below.

As we can see from the figure that data members/function of class


A are inherited twice to class D. One through class B and second
through class C. When any data / function member of class A is
accessed by an object of class D, ambiguity arises as to which
data/function member would be called? One inherited through B
or the other inherited through C. This confuses compiler and it
displays error.
Example: To show the need of Virtual Base Class in C++
#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello form A \n";
}
};
class B : public A {
};

class C : public A {
};

class D : public B, public C {


};
int main()
{
D object;
object.show();
}

Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is declared as virtual base class by placing
a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Note:
virtual can be written before or after the public. Now only one copy of data/function member will be copied to class C and
class B and class A becomes the virtual base class. Virtual base classes offer a way to save space and avoid ambiguities in
class hierarchies that use multiple inheritances. When a base class is specified as a virtual base, it can act as an indirect
base more than once without duplication of its data members. A single copy of its data members is shared by all the base
classes that use virtual base.
#include <iostream>
using namespace std;

class A {
public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A {


};
class C : public virtual A {
};

class D : public B, public C {


};
int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;

return 0;
}

Output
a = 10

Questions with answers:

MCQ type: Inheritance - C++ Programming Questions and Answers - Sanfoundry

Broad questions type: CPP Programming Inheritance based Questions Answers - EXAMRADAR

You might also like