Hierarchical Inheritance in C++

Inheritance is the process by which objects of one class acquire the properties of another class. By this we can add additional features to an existing class without modifying it.
This is possible by deriving a new class from the existing one. The new class will have combined features of both the classes.

Hierarchical Inheritance in C++

Hierarchical Inheritance in C++ is that in which a Base class has many sub classes or when a Base class is used or inherited by many sub classes. Thus when more than one classes are derived from a single base class, such inheritance is known as Hierarchical Inheritance, where features that are common in lower level are included in parent class.

Hierarchical Inheritance in C++

class base_class_name
{
private:
…………….
public:
…………….
};
class derived_class_name1 : public base_class_name
private:
……………
public:
……………
};
class derived_class_name2 : public base_class_name
private:
…………..
public:
…………..
};
Example Program of Hierarchical Inheritance in C++

Run Online

#include <iostream> 
using namespace std;
class Side
{
	protected:
	int l;
	public:
	void set_values (int x)
	{ l=x;}
}; 
class Square: public Side
{
	public:
	int sq()
	{ return (l *l); }
}; 
class Cube:public Side
{
	public:
	int cub()
	{ return (l *l*l); }
}; 
int main ()
{
	Square s;
	s.set_values (10);
	cout << "The square value is::" << s.sq() << endl;
	Cube c;
	c.set_values (20);
	cout << "The cube value is::" << c.cub() << endl;
	return 0;
}
Output
Total Objects: 1
The square value is:: 100
The cube value is::8000
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *