The document discusses different types of inheritance in C++ including single, multilevel, multiple, hybrid, and hierarchical inheritance. It provides code examples to illustrate each type. Single inheritance allows a derived class to inherit from one base class. Multilevel inheritance involves deriving a class from another derived class. Multiple inheritance allows a class to inherit from multiple base classes. Hybrid inheritance combines more than one type of inheritance. Hierarchical inheritance derives multiple classes from a common base class.
2. Inheritance:
● In C++, inheritance is a process in which one
object acquires all the properties and behaviors
of its parent object automatically.
Advantage of C++ Inheritance:
● Code reusability: we can reuse the members of
your parent class. So, there is no need to define
the member again. So less code is required in
the class.
4. Single inheritance is defined as the inheritance in
which a derived class is inherited from the only
one base class.
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
6. Multilevel inheritance is a process of deriving a
class from another derived class.
● #include <iostream>
● using namespace std;
● class Animal {
● public:
● void eat() {
● cout<<"Eating..."<<endl;
● }
● };
7. ● class Dog: public Animal
● {
● public:
● void bark(){
● cout<<"Barking..."<<endl;
● }
● };
● class BabyDog: public Dog
● {
● public:
9. Multiple inheritance is the process of deriving a
new class that inherits the attributes from two or
more classes.
● #include<iostream>
● using namespace std;
● class MyClass {
● public:
● void myFunction() {
● cout << "Some content in parent class.n" ;
● }};
10. ● class MyOtherClass {
● public:
● void myOtherFunction() {
● cout << "Some content in another class." ;
● }
● };
● class MyChildClass: public MyClass, public
MyOtherClass {
● };
12. Hybrid inheritance is a combination of more than
one type of inheritance.
● #include <iostream>
● using namespace std;
● class A
● { public:
● int x;};
● class B : public A
13. ● { public:
● B()
● {x = 10; }};
● class C
● {
● public:
● int y;
● C()
● {
● y = 4; }};
14. ● class D : public B, public C
● { public:
● void sum()
● {cout << "Sum= " << x + y;}
● };
● int main()
● { D obj1;
● obj1.sum();
● return 0;
● }
15. Hierarchical inheritance is defined as the process
of deriving more than one class from a base class.
● #include <iostream>
● using namespace std;
● class Side
● { protected:
● int l;
● public:
● void set_values (int x)
● { l=x;}};
16. ● 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;
17. 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;}