Cpp
Cpp
Inheritance is a mechanism of acquiring the features and behaviors of a class by another class.
The class whose members are inherited is called the base class, and the class that inherits
those members is called the derived class. Inheritance implements the IS-A relationship.
● Single Inheritance
● Multiple Inheritance
● Multilevel Inheritance
● Hierarchical Inheritance
● Hybrid Inheritance
1) Single Inheritance
In single inheritance, a class derives from one base class only. This means that there is
only one subclass that is derived from one superclass.
};
Given below is a complete Example of Single Inheritance.
#include <iostream>
#include <string>
class Animal
string name="";
public:
int tail=1;
int legs=4;
};
public:
void voiceAction()
cout<<"Barks!!!";
};
int main()
Dog dog;
cout<<"Dog has "<<dog.legs<<" legs"<<endl;
cout<<"Dog ";
dog.voiceAction();
Output:
Dog Barks!!!
We have a class Animal as a base class from which we have derived a subclass dog. Class
dog inherits all the members of Animal class and can be extended to include its own
properties, as seen from the output.
In a real-life scenario, a child inherits from its father and mother. This can be considered as
an example of multiple inheritance.
class student_marks {
protected:
public:
void get() {
cout << "Enter the Roll No.: "; cin >> rollNo;
cout << "Enter the two highest marks: "; cin >> marks1 >> marks2;
};
class cocurricular_marks {
protected:
int comarks;
public:
void getsm() {
cout << "Enter the mark for CoCurricular Activities: "; cin >>
comarks;
};
public:
void display()
{
avg_marks = total_marks / 3;
cout << "\nRoll No: " << rollNo << "\nTotal marks: " <<
total_marks;
};
int main()
Result res;
Output:
Roll No: 25
Average marks: 40
In the above example, we have three classes i.e. student_marks, cocurricular_marks, and
Result. The class student_marks reads the subject mark for the student. The class
cocurricular_marks reads the student’s marks in co-curricular activities.
The Result class calculates the total_marks for the student along with the average marks.
Diamond problem
As shown in the figure, class Child inherits the traits of class Person twice i.e. once from
Father and the second time from Mother. This gives rise to ambiguity as the compiler fails to
understand which way to go.
Since this scenario arises when we have a diamond-shaped inheritance, this problem is
famously called “The Diamond Problem”.
#include <string>
class Animal
string name="";
public:
int tail=1;
int legs=4;
};
{
public:
void voiceAction()
cout<<"Barks!!!";
};
public:
void weeping()
cout<<"Weeps!!";
};
int main()
Puppy puppy;
cout<<"Puppy ";
puppy.voiceAction();
puppy.weeping();
Output:
Hybrid inheritance is usually a combination of more than one type of inheritance. In the
above representation, we have multiple inheritance (B, C, and D) and multilevel inheritance
(A, B and D) to get a hybrid inheritance.
#include <string>
int id;
string name;
public:
void getstudent(){
};
int marks_math,marks_phy,marks_chem;
public:
void getmarks(){
};
class sports{
protected:
int spmarks;
public:
void getsports(){
};
int total_marks;
float avg_marks;
public :
void display(){
total_marks=marks_math+marks_phy+marks_chem;
avg_marks=total_marks/3.0;
};
int main(){
result res;//object//
res.getstudent();
res.getmarks();
res.getsports();
res.display();
return 0;
}
Output:
Here we have four classes i.e. Student, Marks, Sports, and Result. Marks are derived from
the student class. The class Result derives from Marks and Sports as we calculate the
result from the subject marks as well as sports marks.
The output is generated by creating an object of class Result that has acquired the
properties of all the three classes.
Note that in hybrid inheritance as well, the implementation may result in “Diamond Problem”
which can be resolved using “virtual” keyword as mentioned previously.
5) Hierarchical Inheritance
In hierarchical inheritance, more than one class inherits from a single base class as shown
in the representation above. This gives it a structure of a hierarchy.
public:
int x,y;
x= n;
y = m;
};
{
public:
int area_rect() {
return area;
};
public:
int triangle_area() {
return area;
};
class Square : public Shape // inherit Shape class
public:
int square_area() {
return area;
};
int main()
{ Rectangle r;
Triangle t;
Square s;
int length,breadth,base,height,side;
//area of a Rectangle
std::cout << "Enter the length and breadth of a rectangle: ";
cin>>length>>breadth;
r.get_data(length,breadth);
//area of a triangle
std::cout << "Enter the base and height of the triangle: ";
cin>>base>>height;
t.get_data(base,height);
//area of a Square
std::cout << "Enter the length of one side of the square: ";
cin>>side;
s.get_data(side,side);
return 0;
Output:
The above example is a classic example of class Shape. We have a base class Shape and
three classes i.e. rectangle, triangle, and square are derived from it.
We have a method to read data in the Shape class while each derived class has its own
method to calculate area. In the main function, we read data for each object and then
calculate the area.
Access Control and Inheritance
A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of derived
classes should be declared private in the base class.
We can summarize the different access types according to - who can access them in
the following way −
#include <iostream>
using namespace std;
// base class
class Parent
{
public:
// sub class
class Child : public Parent
{
public:
// main function
int main() {
return 0;
}
Output:
Example 2:
// C++ program to show the order of constructor calls
// in Multiple Inheritance
#include <iostream>
using namespace std;
public:
// main function
int main() {
Example 3:
// C++ program to show how to call parameterised Constructor
// of base class when derived class's Constructor is called
#include <iostream>
using namespace std;
// base class
class Parent
{
public:
// sub class
class Child : public Parent
{
public:
// main function
int main() {
Output:
Inside base class's parameterised constructor
Inside sub class's parameterised constructor
Containership in C++
We can create an object of one class into another and that object will be a member of
the class. This type of relationship between classes is known as containership or
has_a relationship as one class contain the object of another class. And the class which
contains the object and members of another class in this kind of relationship is called a
container class.
The object that is part of another object is called as contained object, whereas
object that contains another object as its part or attribute is called container
object.
Containership
-> When features of existing class are wanted inside your new class, but, not its
interface
for eg->
Inheritance
-> When you want to force the new type to be the same type as the base class.
for eg->
2)Car is a vehicle
Employees can be of Different types as can be seen above. It can be a developer, an HR
manager, a sales executive, and so on. Each one of them belongs to Different problem domain
but the basic Characteristics of an employee are common to all.
// Container class
class second {
● Whenever the derived class’s default constructor is called, the base class’s
default constructor is called automatically.
● To call the parameterised constructor of base class inside the
parameterised consructor of sub class, we have to mention it explicitly.
● The parameterised constructor of base class cannot be called in default
constructor of sub class, it should be called in the parameterised constructor
of sub class.
#include <iostream>
using namespace std;
class first {
public:
void showf()
{
cout << "Hello from first class\n";
}
};
// Container class
class second {
// creating object of first
first f;
public:
// constructor
second()
{
// calling function of first class
f.showf();
}
};
int main()
{
// creating object of second
second s;
}
Output:
Hello from first class
#include <iostream>
class first {
public:
first()
};
// Container class
class second {
first f;
public:
// constructor
second()
};
int main()
second s;
Output:
class cDate
int mDay,mMonth,mYear;
public:
cDate()
mDay = 10;
mMonth = 11;
mYear = 1999;
mDay = d;
mMonth = m;
mYear = y;
void display()
};
// Container class
class cEmployee
protected:
int mId;
int mBasicSal;
// Contained Object
cDate mBdate;
public:
cEmployee()
mId = 1;
mBasicSal = 10000;
mBdate = cDate();
void display();
};
cEmployee :: cEmployee(int i, int sal, int d, int m, int y)
mId = i;
mBasicSal = sal;
mBdate = cDate(d,m,y);
void cEmployee::display()
mBdate.display();
int main()
cEmployee e1;
e1.display();
cEmployee e2(2,20000,11,11,1999);
e2.display();
return 0;
output
Id : 1
Salary :10000
day 10
Month 11
Year 1999
Id : 2
Salary :20000
day 11
Month 11
Year 1999
Virtual Function in C++
Normal member function accessed with pointers:
A virtual function is a member function which is declared within a base class and is
re-defined(Overriden) by a derived class. When you refer to a derived class object using
a pointer or a reference to the base class, you can call a virtual function for that object
and execute the derived class’s version of the function.
● Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
● They are mainly used to achieve Runtime polymorphism
● Functions are declared with a virtual keyword in base class.
● The resolving of function call is done at Run-time.
#include <iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
void show()
{
cout << "show base class" << endl;
}
};
void show()
{
cout << "show derived class" << endl;
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
Late binding(Runtime) is done in accordance with the content of pointer (i.e. location
pointed to by pointer) and Early binding(Compile time) is done according to the type of
pointer, since print() function is declared with virtual keyword so it will be bound at
run-time (output is print derived class as pointer is pointing to object of derived class )
and show() is non-virtual so it will be bound during compile time(output is show base
class as pointer is of base type ).
NOTE: If we have created a virtual function in the base class and it is being overridden
in the derived class then we don’t need virtual keyword in the derived class, functions
are automatically considered as virtual functions in the derived class.
Working of virtual functions(concept of VTABLE and VPTR)
If a class contains a virtual function then compiler itself does two things:
class base {
public:
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
virtual void fun_3() { cout << "base-3\n"; }
virtual void fun_4() { cout << "base-4\n"; }
};
int main()
{
base* p;
derived obj1;
p = &obj1;
base-1
derived-2
base-3
Base-4
Nested Classes in C++
A nested class is a class that is declared in another class. The nested class is also a
member variable of the enclosing class and has the same access rights as the other
members. However, the member functions of the enclosing class have no special
access to the members of a nested class.
A program that demonstrates nested classes in C++ is as follows.
#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
In the above program, class B is defined inside the class A so it is a nested class.
The class B contains a private variable num and two public functions getdata()
and putdata(). The function getdata() takes the data and the function putdata()
displays the data. This is given as follows.