Inheritance
Inheritance
Inheritance
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
C++ Single Inheritance
Output:
Eating...
Barking...
Weeping...
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
Syntax of the Derived class:
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }
Output:
A derived class with two base classes and these two base classes
have one common base class is called multipath inheritance.
Ambiguity can arise in this type of inheritance.
#include <iostream>
using namespace std;
class ClassA {
public:
int a;
};
int main()
{
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
In the above example, both ClassB and ClassC inherit ClassA, they
both have a single copy of ClassA.
However Class-D inherits both ClassB and ClassC, therefore Class-D
has two copies of ClassA, one from ClassB and another from
ClassC.
If we need to access the data member of ClassA through the object
of Class-D, we must specify the path from which a will be
accessed, whether it is from ClassB or ClassC, bcoz compiler can’t
differentiate between two copies of ClassA in Class-D.