Multiple inheritance is a feature in C++ that allows a class to inherit from more than one base class. This means that the derived class can have access to all the members of the base classes that it inherits from.
The need for multiple inheritance arises when a derived class needs to inherit functionality from more than one base class. For example, suppose you want to create a class that represents a square shape in both two-dimensional and three-dimensional space. You could have a base class for two-dimensional shapes and another base class for three-dimensional shapes. By using multiple inheritance, you can create a derived class that inherits from both of these base classes and has access to the functionality of both.
Multiple inheritance can also be used to create a hierarchy of classes with different levels of specialization.
#include <iostream>
using namespace std;
class First{
public:
string name = "Jordan";
void printName() {
cout << "Name: " << name << endl;
}
};
class Second{
public:
string last_name = "Peterson";
void printLastName() {
cout << "Last Name: " << last_name << endl;
}
};
class Third : public First, Second {
public:
void caller() {
printName();
printLastName();
}
};
int main() {
Third Object;
Object.caller();
return 0;
}
In this code, the classes First
and Second
are being inherited publicly by the class Third
, which means that the public and protected members of First
and Second
will be accessible by the objects of Third
.
Third
class has a member function caller()
which calls the member functions of both the base classes, First
and Second
. The printName()
and printLastName()
functions of the First
and Second
classes respectively are being called using the object of the Third
class.
int main() {
Third Object;
Object.caller();
First Obj_1;
Obj_1.printName();
Second Obj_2;
Obj_2.printLastName();
return 0;
}
We have created three objects of three different classes.
The first object Object
is of the class Third
, which inherits from both First
and Second
classes. Object
calls the caller
function, which in turn calls printName
function from First
class and printLastName
function from Second
class. Therefore, when Object.caller()
is executed, it prints out both the name and the last name.
The second object Obj_1
is of the class First
, and we call the printName
function of First
class, which simply prints out the name
variable.
The third object Obj_2
is of the class Second
, and we call the printLastName
function of Second
class, which simply prints out the last_name
variable.
So, in summary, we are able to create objects of different classes and call their respective member functions, and in case of Third
class object, it is able to call member functions of both First
and Second
classes because it inherits from both of them.
No comments:
Post a Comment