You are on page 1of 7

5_classes

Multi-level Inheritance

a derived class is
created from another
derived class.
#include <iostream>
using namespace std;
// base class Example
class Vehicle
{
public:
Vehicle() // main function
{ int main()
cout << "This is a Vehicle" << endl; {
} //creating object of sub class will
};
//invoke the constructor of base classes
class fourWheeler: public Vehicle
{ public: Car obj;
fourWheeler() return 0;
{ }
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
public:
car() output:
{
cout<<"Car has 4 Wheels"<<endl; This is a Vehicle
} Objects with 4 wheels are vehicles
}; Car has 4 Wheels
Hierarchical Inheritance

More than one sub class is inherited from a single base


class. i.e. more than one derived class is created from a
single base class.
#include <iostream>
using namespace std;
// base class
class Vehicle
Example
{
public: // main function
Vehicle() int main()
{ {
cout << "This is a Vehicle" << endl; // creating object of sub class will
} // invoke the constructor of base class
}; Car obj1;
Bus obj2;
return 0;
// first sub class }
class Car: public Vehicle
{

};

// second sub class Output:


class Bus: public Vehicle
{ This is a Vehicle
This is a Vehicle
};
Hybrid Inheritance

Hybrid Inheritance is
implemented by combining
more than one type of
inheritance. For example:
Combining Hierarchical
inheritance and Multiple
Inheritance.
#include <iostream>
using namespace std;
Example
// first sub class
// base class
class Car: public Vehicle
class Vehicle
{ {
public: };
Vehicle()
{ // second sub class
cout << "This is a Vehicle" << endl; class Bus: public Vehicle, public Fare
} {
}; };
//base class // main function
class Fare int main()
{
{
public:
Fare() // creating object of sub class will
{ // invoke the constructor of base class
cout<<"Fare of Vehicle\n"; Bus obj2;
} return 0;
}; } Output:

This is a Vehicle
Fare of Vehicle

You might also like