0% found this document useful (0 votes)
1 views41 pages

OOP (CO1201) Unit-4 - Inheritance in C++

This document provides an overview of inheritance in C++, detailing the concepts of base and derived classes, as well as various types of inheritance such as single, multilevel, multiple, hierarchical, and hybrid inheritance. It includes examples of class definitions and the use of access specifiers, function overriding, and the 'this' pointer. Additionally, it addresses the diamond problem and how virtual base classes can resolve ambiguity in multiple inheritance scenarios.

Uploaded by

harsh.parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views41 pages

OOP (CO1201) Unit-4 - Inheritance in C++

This document provides an overview of inheritance in C++, detailing the concepts of base and derived classes, as well as various types of inheritance such as single, multilevel, multiple, hierarchical, and hybrid inheritance. It includes examples of class definitions and the use of access specifiers, function overriding, and the 'this' pointer. Additionally, it addresses the diamond problem and how virtual base classes can resolve ambiguity in multiple inheritance scenarios.

Uploaded by

harsh.parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT 4: Inheritance in C++

Prepared By,
Ms.Anuja Gunale
Introduction
 In C++, it is possible to inherit attributes and methods
from one class to another. We group the "inheritance
concept" into two categories:

 derived class (child) - the class that inherits from another


class
 base class (parent) - the class being inherited from
 To inherit from a class, use the : symbol.

 In the example below, the Car class (child) inherits the


attributes and methods from the Vehicle class (parent):
Inheritance
C++ Inheritance
 One of the most important concepts in object-oriented
programming is that of inheritance.
 Inheritance allows us to define a class in terms of
another class, which makes it easier to create and
maintain an application.
 This also provides an opportunity to reuse the code
functionality and fast implementation time.
 When creating a class, instead of writing completely
new data members and member functions, the
programmer can designate that the new class should
inherit the members of an existing class.
 This existing class is called the base class, and the
new class is referred to as the derived class.
C++ Inheritance

Inheritance is the process by which new classes called


derived classes are created from existing classes called
base classes.

The derived classes have all the features of the base


class and the programmer can choose to add new
features specific to the newly created derived class.
C++ Inheritance

General Format for implementing the concept of


Inheritance:

class derived_classname: access specifier baseclassname

For example, if the base class is MyClass and the derived class
is sample it is specified as:

class sample: public MyClass

The above makes sample have access to both public and


protected variables of base class MyClass
public, private and protected access specifiers:

1 If a member or variables defined in a class is private, then they are


accessible by members of the same class only and cannot be
accessed from outside the class.

2 Public members and variables are accessible from outside the class.

3 Protected access specifier is a stage between private and public. If a


member functions or variables defined in a class are protected, then
they cannot be accessed from outside the class but can be accessed
from the derived class.
C++ Inheritance
Inheritance Example:

class MyClass
{ public:
MyClass(void) { x=0; }
void f(int n1)
{ x= n1*5;}
void output(void) { cout<<x; }
private:
int x;
};
Inheritance Example:

class sample: public MyClass


{
public:
sample(void)
{
s1=0;
}
void f1(int n1)
{
s1=n1*10;
}
void output(void)
{
MyClass::output();
cout << s1;
}
private:
int s1;
};
Inheritance Example:

int main(void)
{ sample s;
s.f(10);
s.output();
s.f1(20);
s.output();
}

The output of the above program is


50
200
Types of Inheritance
1. Single class Inheritance:

Single inheritance is the one where you have a


single base class and a single derived class.

Class Employee It is a Base class (super)

Class Manager it is a sub class (derived)


Single Inheritance
 A class can also be derived from one class, which is already derived from another class.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
} Output:
Eating...
};
Barking...
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
Types of Inheritance
2. Multilevel Inheritance:
In Multi level inheritance, a class inherits its
properties from another derived class.

Class A it is a Base class (super) of B

Class B it is a sub class (derived) of A


and base class of class C

Class C derived class(sub) of class B


Multilevel Inheritance
 A class can also be derived from one class, which is already derived from another class.
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
} Output:
}; Eating...
int main(void) { Barking...
BabyDog d1; Weeping...
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Types of Inheritance
3. Multiple Inheritances:

In Multiple inheritances, a derived class inherits


from multiple base classes. It has properties of
both the base classes.

Class A Class B Base class

Class C Derived class


Multiple Inheritance
 A class can also be derived from one class, which is already derived from another class.
#include <iostream>
using namespace std;
class A
{ class C : public A,public B
protected: {
int a; public:
public: void display()
void get_a(int n) {
{ std::cout << "The value of a is
a = n; : " <<a<< std::endl;
} std::cout << "The value of b is
}; : " <<b<< std::endl;
cout<<"Addition of a and b is :
class B "<<a+b;
{ }
protected: };
int b; int main()
public: { Output:
void get_b(int n) C c; The value of a is : 10
{ c.get_a(10);
The value of b is : 20
b = n; Addition of a and b is : 30
c.get_b(20);
} c.display();
};
return 0;
}
Types of Inheritance
4. Hierarchical Inheritance:

In hierarchical Inheritance, it's like an inverted tree.


So multiple classes inherit from a single base
class. It's quite analogous to the File system in a
unix based system.

Class A

Class B Class D Class C


Hierarchical Inheritance
class Triangle : public Shape // inheriting Shape class
{
#include <iostream> public:
using namespace std; int triangle_area()
class Shape // Declaration of base clas {
s. float result = 0.5*a*b;
{ return result;
public: }
int a; };
int b; int main()
void get_data(int n,int m) {
{ Rectangle r;
a= n; Triangle t;
b = m; int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl Output:
} Enter the length and breadth
}; ;
of a rectangle: 23 20
class Rectangle : public Shape // inher cin>>length>>breadth;
Area of the rectangle is : 460
iting Shape class r.get_data(length,breadth); Enter the base and height of
{ int m = r.rect_area(); the triangle: 2 5
public: std::cout << "Area of the rectangle is : " <<m<< std::endl; Area of the triangle is : 5
int rect_area() std::cout << "Enter the base and height of the triangle: " << std::endl;
{ cin>>base>>height;
int result = a*b; t.get_data(base,height);
return result; float n = t.triangle_area();
} std::cout <<"Area of the triangle is : " << n<<std::endl;
}; return 0;
}
Types of Inheritance
5. Hybrid Inheritance:
In this type of inheritance, we can have mixture of
number of inheritances but this can generate an
error of using same name function from no of
classes, which will bother the compiler to how to
use the functions.
Therefore, it will generate errors in the program.
This has known as ambiguity or duplicity.
Ambiguity problem can be solved by using virtual
base classes
Types of Inheritance
5. Hybrid Inheritance:

Class A

Class B Class C

Class D
Hybrid Inheritance class C
{
protected:
#include <iostream>
int c;
using namespace std;
public:
class A
void get_c()
{
{
protected:
cout << "Enter the value of c is : " << endl;
int a;
cin>>c;
public:
}
void get_a()
};
{
class D : public B, public C
cout << "Enter the value of 'a' : " <<
{
endl;
protected:
cin>>a;
int d;
}
public:
};
void mul()
{
class B : public A
get_a();
{
get_b();
protected:
get_c(); Output:
int b;
cout << "Multiplication of a,b,c is : " <<a*b*c<< endl; Enter the length and breadth
public:
} of a rectangle: 23 20
void get_b() Area of the rectangle is : 460
};
{ Enter the base and height of
int main()
cout << "Enter the value of 'b' : " < the triangle: 2 5
{
< endl; Area of the triangle is : 5
D d;
cin>>b;
d.mul();
}
return 0;
}
}
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
Output:
cout<<C.add(12, 20, 23);
30 55
return 0;
}
#include <iostream>
using namespace std;
Function Overriding class Animal
{
public:
 If derived class defines same void eat()
function as defined in its base {
class, it is known as function cout<<"Eating...";
overriding in C++. }
 It is used to achieve runtime };
polymorphism. class Dog: public Animal
{
 It enables you to provide public:
specific implementation of the void eat()
function which is already {
provided by its base class. cout<<"Eating bread...";
}
};
int main(void)
{
Dog d = Dog(); Output:
d.eat(); Eating bread...

return 0;
}
Virtual Base Class
Example Without Virtual Base Class
 In C++, a virtual base class is a type of cpp
base class that is specified using the class A
 virtual keyword when it is inherited. This is {
particularly useful in the context of public: void show()
multiple inheritance,
 where it helps solve the diamond
{
problem. std::cout << "Class A" << std::endl;
}
 The Diamond Problem };
 The diamond problem occurs when a class class B1 : public A {};
D inherits from two classes B1 and B2, class B2 : public A {};
which both inherit from the same base class D : public B1, public B2 {};
class A. int main()
 This can lead to ambiguity, as D could end
up with two copies of A—one through B1
{
and one through B2. D d;
d.show(); // Error: Ambiguity, which "show()" method to call?
}

In this example, class D will have two copies of A,


leading to ambiguity when trying to call a method from A.
Solving with Virtual Base Class
To resolve this issue, you can declare A as a virtual base class:

class A
{
public: void show()
{
std::cout << "Class A" << std::endl;
}
};
class B1 : public virtual A { };
class B2 : public virtual A { };
class D : public B1, public B2 { };
int main()
{
D d;
d.show(); // No ambiguity, single copy of A
}

Here, A is declared as a virtual base class,


which ensures that D only contains a single copy of A, thus avoiding ambiguity.
Key Points:
•Virtual base classes are used to solve the diamond problem by
ensuring
that only one instance of the base class is created, regardless of how
many times
it is inherited indirectly.
•They are particularly useful in complex inheritance hierarchies where
multiple
inheritance is involved.
•Virtual base classes are specified using the virtual keyword during
inheritance.
This pointer
This pointer
 The this pointer is a pointer accessible
only within the nonstatic member
functions of a class , struct , or union
type.
 It points to the object for which the
member function is called.
 Static member functions don't have a
this pointer.
This pointer
 Everyobject in C++ has access to its own
address through an important pointer called
this pointer.
 The
this pointer is an implicit parameter to all
member functions.
 Therefore,inside a member function, this may
be used to refer to the invoking object.
#include<iostream.h> int main()
class Test {
{ Test obj;
int x; int x = 20;
public: obj.setX(x);
void setX (int x) obj.print();
{ return 0;
this->x = x; }
}
void print() { cout << "x = " << x << endl; }
};
#include <iostream.h>
class sample
{
int main()
int a,b; {
public: sample x;
void input(int a,int b)
x.input(5,8);
{
this->a=a+b; x.output();
this->b=a-b; getch();
}
return 0;
void output()
{
}
cout<<"a = "<<a<<endl<<"b = "<<b;
}
};

You might also like