Q.4) Explain Different Types of Inheritance With Suitable Examples of Each Type. Ans
Q.4) Explain Different Types of Inheritance With Suitable Examples of Each Type. Ans
Ans.
Inheritance is the technique for creating new class (derived classes) from the existing
classes (base classes). Derived class inherits the some or all feature of base class.
-Single Inheritance
-Multiple Inheritance
-Hierarchical Inheritance
-Multilevel Inheritance
-Hybrid Inheritance
-Multipath Inheritance
Public, Protected and Private
Inheritance in C++ Programming
In this article, you'll learn to use public, protected and private inheritance in C+
+. You'll learn where and how it is used, with examples.
You can declare a derived class from a base class with different access control,
i.e., public inheritance, protected inheritance or private inheritance.
#include <iostream>
class base
};
};
yes
Accessible from derived
no yes (inherited as protected
class?
variables)
variables) variables)
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal()
{
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal()
{
cout << "Winged animal can flap." << endl;
}
};
};
int main()
{
Bat b1;
return 0;
}
Output
Suppose, two base classes have a same function which is not overridden in
derived class.
If you try to call the function using the object of the derived class, compiler
shows error. It's because compiler doesn't know which function to call. For
example,
class base1
{
public:
void someFunction( )
{ .... ... .... }
};
class base2
{
void someFunction( )
{ .... ... .... }
};
class derived : public base1, public base2
{
};
int main()
{
derived obj;
obj.someFunction() // Error!
}
This problem can be solved using scope resolution function to specify which
function to class either base1 or base2
int main()
class A
{
... .. ...
};
class B: public A
... .. ...
};
class C: public B
};
Here, class B is derived from the base class A and the class C is derived from
the derived classB.
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C obj;
obj.display();
return 0;
}
Output
The compiler first looks for the display() function in class C. Since the function
doesn't exist there, it looks for the function in class B (as C is derived from B).
The function also doesn't exist in class B, so the compiler looks for it in
class A (as B is derived from A).