[go: up one dir, main page]

0% found this document useful (0 votes)
6 views56 pages

Unit IIInheritance T1742060295831

Uploaded by

parthchatupale8
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)
6 views56 pages

Unit IIInheritance T1742060295831

Uploaded by

parthchatupale8
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/ 56

Unit – II :- Inheritance

7hrs
Prof. Tahreem Shaikh
Content
1. Inheritance : Class hierarchy , Derived classes
2. Types of inheritance
3. Constructor and Destructor execution in inheritance
4. Ambiguity in Multiple Inheritance
5. Virtual Base Class
6. Abstract class
7. Friend Class
8. Nested Class
Inheritance
1. The classes can be reused in several ways .
2. Once class has been created and tested it can be adapted by other programmer.
This is done by Creating new classes ,reusing the properties of existing one.
the Mechanism of deriving new class from old one is called “Inheritance “

1. Reusability (Code) : is yet another function of OOP

2. C++ Strongly support Feature of Reusability(Code) .

3. It save the time and money and also increase the reliability
Inheritance
• 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.
• Reuse the code functionality and fast
implementation time.
NOTE : All members of a class except Private, are
4

inherited
The old class is referred to as the base class and new class is called the derived
class.
Class hierarchy
A class hierarchy is a group of related classes that are connected through inheritance to do similar things

Example :

The below diagram shows,


Class A is a Base class, B is a subclass inherited from class A, and C is a subclass it also inherits from class A.
Similarly, if another subclass inherits property from B class and so on then there will be a hierarchy, and

a tree-like structure is formed, below is the diagram.


Base Class:

1. A base class is a class in Object-Oriented Programming language, from which other classes are derived.

2. The Base class members and member functions are inherited to Object of the derived class.

3. A base class is also called parent class or superclass.


Derived classes :

1. A class that is created from an existing class.

2. The derived class inherits all members and member functions of a base class.

3. The derived class can have more functionality with respect to the Base class and

can easily access the Base class.

4. A Derived class is also called a child class or subclass.


DEFINING DERIVED CLASSES
A derived class can be defined by specifying its relationship with the base class in addition

to its own details. The general form of defining a derived class is


Implementing inheritance in C++:
For creating a sub-class which is inherited from the base class we have to follow the
below syntax.
Access Mode is used to specify, the mode in which the properties of
superclass will be inherited into subclass -
class Subclass_name : access_mode Base_class_name

//body of subclass

};

Access Mode May be -> public, protected, private


A derived class inherits all base class methods with the
following exceptions:

• Constructors, destructors and copy


constructors of the base class.
• Overloaded operators of the base class.
• The friend functions of the base class
12
Inheritance & it’s Type
Inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically
Inheritance & it’s Type
 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
Single Inheritance
In single inheritance, a class derives from one base class only. This means that there is only
one subclass that is derived from one superclass.
#include <iostream>
using namespace std;
int main(void)
class Animal {
{
public: Dog d1;
void eat()
{ d1.eat();
cout<<"Eating..."<<endl;
d1.bark();
}
return 0;
};
}
class Dog: public Animal
Animal
{
public:
void bark()
{
cout<<"Barking..."; Dog
}
};
// C++ program to explain Single inheritance
#include <iostream.h>
#include <conio.h>

class Vehicle
{ Vehicle
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
}; Car

class Car : public Vehicle


{
public:
Car()
{
cout << “I am in car class " << endl;
}
};

Int main()
{
Clrscr();
Car obj; // as soon as object created it call the Constructor of Vehicle & Car class
return 0;
}
Multilevel Inheritance

The inheritance in which a class can be derived


from another derived class is known as Multilevel
Inheritance

Suppose there are three classes A, B, and C.


A is the base class that derives from class B.
So, B is the derived class of A.
Now, C is the class that is derived from class B.

Inheritance is transitive so the last derived class acquires all the members of all its base
classes.
Animal

Dog

BabyDog Here BabyDog can access Dog and Animal class member
#include <iostream> class BabyDog : public Dog
{
using namespace std; public:
void weep()
class Animal {
{ cout<<"Weeping...";
public: }
void eat() };
{
cout<<"Eating..."<<endl; int main(void)
} {
}; BabyDog d1;

d1.eat();
class Dog: public Animal d1.bark();
{ d1.weep();
public: return 0;
void bark()
{ }
cout<<"Barking..."<<endl;
}
};
Multiple Inheritance
Multiple Inheritance is a feature of C++ where a class can inherit from more
than base one classes.

i.e one sub class is inherited from more than TWO base classes.
Multiple Inheritance
Syntax:
class subclass_name : access_mode Base_class1, access_mode Base_class2, ….
{
//body of subclass
};

Vehicle Fourwheeler

Car
#include <iostream>
class C : public A, public B
using namespace std;
{
class A public:
{
protected: void display()
int a; {
public: cout << "The value of a is : " <<a<< endl;
void get_a(int n) cout << "The value of b is : " <<b<< endl;
{ cout<<"Addition of a and b is : "<<a+b;
a = n; }
};
}
};
class B int main()
{ {
protected: C c;
int b; c.get_a(10);
public: c.get_b(20);
void get_b(int n) c.display();
{
return 0;
b = n;
}
}
};
Example of Multiple Inheritance

#include <iostream.h> // sub class derived from two base classes


#include <conio.h>

class Vehicle // first base class


{ class Car: public Vehicle, public FourWheeler
public: {
Vehicle() // Constructor public:
{ Car() // Constructor
{
cout << "This is a Vehicle" << endl; cout << "This is a car " << endl;
} }
};
};

class FourWheeler // second base class int main()


{ {
// creating object of sub class will
public:
// invoke the constructor of base
FourWheeler()
{ Car obj;
cout << "This is a 4 wheeler Vehicle" << endl; return 0;
} }
};
Hierarchical Inheritance
Hierarchical Inheritance​​ If more than one class is inherited from the base
class
class C : public A //C is also derived from class base A
#include <iostream>
{
using namespace std;
public:
class A // Base class
void sum()
{
{
public:
cout<< "\nSum= " << x + y;
int x, y;
}
void getdata() // to input x and y
};
{
cout<< "Enter value of x and y:\n";
cin>> x >> y;
int main()
}
{
};
B obj1;
class B : public A //B is derived from class base A
C obj2;
{
public:
obj1.getdata();
void product()
obj1.product();
{
cout<< "\n Product= " << x * y <<endl;
obj2.getdata();
}
obj2.sum();
};
}
Hybrid inheritance

The process of combining more than one type of Inheritance together


while deriving subclasses in a program is called a Hybrid Inheritance.

Combining various types of inheritance like multiple, simple, and


hierarchical inheritance is known as hybrid inheritance.
#include<iostream>
using namespace std; class daughter: public father
{
class Grand_father public:
{ void daughter_f()
public: {
void gf() cout<<"I am daughter "<<endl;
{ }
cout<<"I am Grand_father "<<endl;
}
};
};
class father: public Grand_father int main()
{ {
public: son s;
void f() daughter d;
{
cout<<"I am father "<<endl; s.gf();
}
};
d.gf();
class son: public father
{ s.f();
public: d.f();
void son_f()
{ s.son_f();
cout<<"I am son "<<endl; d.daughter_f();
} }
};
Constructor and Destructor execution in inheritance
Let us look at below example to understand what happens –
Constructor and Destructor execution in inheritance

1. Constructor in C++ is a special method that is invoked automatically at the time of


object creation

2. Destructor is always called in the reverse order of the constructor. In C++, variables
and objects are allocated on the Stack.

3. The Stack follows the LIFO (Last-In-First-Out) pattern. So, the deallocation of memory
and destruction is always carried out in the reverse order of allocation and construction.

4. Destructor is a special class function which destroys the object as soon as the scope of
object ends
#include <iostream>
class C :public B
using namespace std;
class A {
{ public:
public: C()
A() {
{ cout<<"C's Constructor"<<endl;
cout<<"A's Constructor"<<endl; }
} ~C()
~A()
{
{
cout<<"A's Destructor"<<endl; cout<<"C's Destructor"<<endl;
} }
}; };
class B :public A int main()
{ {
public: C c;
B() return 0;
{
}
cout<<"B's Constructor"<<endl;
} A's Constructor
~B()
B's Constructor
{
cout<<"B's Destructor"<<endl;
C's Constructor
} C's Destructor
}; B's Destructor
A's Destructor
#include <iostream> class child : public parent
using namespace std; {
public:
class parent //parent class child() //constructor
{ {
public: cout << "Child class Constructor\n";
}
parent() //constructor
{ ~ child() //destructor
cout << "Parent class Constructor\n"; {
} cout << "Child class Destructor\n";
}
~parent()//destructor };
{
cout << "Parent class Destructor\n"; int main()
} {
//automatically executes both child and
}; parent class
//constructors and destructors because of
inheritance

child c;
return 0;
}
Ambiguity in Multiple Inheritance
1. A derived class with two base classes and these
two base classes have one common base class is
called multipath inheritance.

2. An ambiguity can arrise in this type of


inheritance.
1. As we can see from the figure that data members/

function of class A are inherited twice to class D. One


through class B and second through class C.
2. When any data / function member of class A is accessed
by an object of class D, ambiguity arises as to which
data/function member would be called ? Either from
inherited through B or the other inherited through C.
Because compiler can’t differentiate between two
copies of Class A in Class D.
1. in such situation compiler get confuse and it displays
error like “request manner is Ambiguos”
#include <iostream> int main()
using namespace std; {
D obj;
class A { obj.show(); //show the ambiguous error
public:
void show() }
{
cout << "Hello form A \n"; ERROR :
} request for member 'show' is ambiguous
};

class B : public A
{
};

class C : public A
{
};

class D : public B, public C


{
};
There are 2 ways to avoid this ambiguity:

A. Using scope resolution operator we can manually specify the path from which
data member a will be accessed

B. Avoiding ambiguity using virtual base class:


Ambiguity using avoid Scope Resolution & Virtual
Base class
1. Using scope resolution operator we can manually specify the path from which data
member a will be accessed
2. Form above Example But Still, there are two copies of Class A in Class D.

1. To avoid multiple copies use virtual base class


2. Avoid ambiguity use Virtual Base class
Ambiguity using avoid Scope Resolution
1. Using scope resolution :: operator we can manually specify the path from which
data member a will be accessed

2. But Problem is Derived class still having the two copies from base class shown in
below example
#include<iostream.h> int main()
#include<conio.h> {
D ob;
class A ob.C::show(); //use :: by specifying the path through class C
{ ob.B::show(); // use :: by specifying the path through class B
public : return 0;
void show() }
{
cout<<“A function is called ";
}
}; Note : Still, there are two copies of Class A in Class D.

class B : public A
{
};

class C : public A
{
};

class D : public B , public C


{
};
Virtual Base Class

Virtual base classes are used in virtual inheritance in a way of


preventing multiple “instances” of a given class appearing in an inheritance
hierarchy when using “multiple inheritances “.

To avoid multiple copies use virtual base class


class A EXAMPLE
{
.....
};
class B1 : virtual public A
{
.....
};
class B2 : virtual public A
{
.....
};
class C : public B1, public B2 43
{
.....// only one copy of A
.....// will be inherited
};
Need of Virtual Base class

1. Using scope resolution operator we can manually specify the path


from which data member a will be accessed and solve the
ambiguity but still the inherited class receives the multiple copies
of form the base classes
2. To solve the multiple copies of form the base classes Virtual Base
class are used
3. To avoid multiple copies use virtual base class
1. As we can see from the figure that data members/

function of class A are inherited twice to class D. One


through class B and second through class C.
2. When any data / function member of class A is accessed
by an object of class D, ambiguity arises as to which
data/function member would be called ? Either from
inherited through B or the other inherited through C.
Because compiler can’t differentiate between two
copies of Class A in Class D.
1. in such situation compiler get confuse and it displays
error like “request manner is Ambiguos”
#include <iostream>

class A {
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : public A
{
};

class C : public A
{
};
class D : public B, public C
{
};
int main()
{
D object;
object.show();
}
#include<iostream.h> int main()
#include<conio.h> {
// Avoid Ambiguity by using Virtual Base class
class A D ob;
{
public : ob.show(); // call the Class A function without Ambigiuty
void show()
{ getch();
cout<<“A is called "; return 0;
} }
};

class B: virtual public A


{
};
Note : only one copies of Class A in Class D.
class C: virtual public A
{ Now Class A is Virtual Class , So Class D has get
}; Only One Copy of A function & data member, so
here Virtual Base class avoid the ambiguity
class D:public B,public C
{
};
Abstract class
1. The C++ interfaces are implemented using abstract classes and these abstract classes.
2. A class is made Abstract by declaring at least one of its functions as pure virtual function
3. A pure virtual function is specified by placing "= 0" in its declaration as follows

4. A class is abstract if it has at least one pure virtual function.

// An abstract class

class Test
{
// Data members of class
public:
MAKE ABSTRACT CLASS // Pure Virtual Function
virtual void show() = 0;

/* Other members */
};
Why Abstract class ?
1. The purpose of an abstract class is to provide an appropriate base class from which other classes (Derived)
can inherit.

2. Abstract classes cannot be used to Create objects and serves only as an interface.

3. We are not able to create the object of Abstract class , if we try to create the object compiler show error

4. A pure virtual function (or abstract function) in C++ is a virtual function for which we can have
implementation, If we do not override the pure virtual function in derived class, then derived class also
becomes abstract class.

5. Failure to override a pure virtual function in a derived class, then attempting to create objects of that class,
is a compilation error.

6. Classes that can be used to create objects are called concrete classes.
A pure virtual function is implemented by classes which are derived from a Abstract class.

#include<iostream> int main(void)


class Base {
{ Derived d;

public: d.fun();
virtual void fun() = 0;
}; return 0;
}
// This class inherits from Base and implements fun()

class Derived : public Base


{
public:
void fun()
{
cout << "fun() called";
}
};
// Abstarct class Demo
#include<iostream.h>
#include<conio.h>

class Test
{
public:
int x;

/* Pure virtual function make the class Abstract class */

virtual void show()=0; // Pure Virtual Function


};

int main()
{

/*If class is ABC(Abstract class) then we are NOT able to create the object of abstract class */

Test t;

/* if you try to create the Object of Abstract class it show Error */

return 0;
}
Friend Class
1. We can also make a class a friend of another class.
2. In that case, all the member function of the class declared as friend become the friend
functions of the other class. Let's see how to make a class a friend of another.

class A
{
friend class B;

};

class B
{

};

Class B is declared as a friend of class A in the above code. So, now all the member functions of class B became friend
functions of class A.
Friend Class in C++
We can also use a friend Class in C++ using the friend keyword.

For example,

class A
{
// Class B is a friend class of Class A

friend class B;
};

class B
{

};

When a class is declared a friend class, all the member functions of the friend class become friend functions.
Since Class B is a friend class, we can access all members of Class A from inside Class B.
#include <iostream>
class Square
{ int getArea()
// declaring Rectangle as friend class {
friend class Rectangle; return length * breadth;
public: }
int side;
};
Square ( int s )
{ int main()
side = s; {
} Square sq(5);
};
class Rectangle Rectangle rec;
{
int length, breadth; rec.shape(sq);

public: cout << rec.getArea() << endl;

void shape( Square obj ) return 0;


{ }
length = obj.side;
breadth = obj.side;
}
Nested Class.
1. A nested class is a class that is declared in another class.

2. The nested class is also a member variable of the enclosing class and has the same access rights as

the other members.

3. However, the member functions of the enclosing class have no special access to the members of a

nested class.
#include<iostream> int main() {
using namespace std;
class A { cout<<"Nested classes in C++"<< endl;
public:
A :: B obj;
class B
{ obj.getdata(9);
private:
int num; obj.putdata();
public:
void getdata(int n) return 0;
{ }
num = n;
}
void putdata()
{
cout<<"The number is "<<num;
}

}; // B is nested inside the class A

}; // End of class A

You might also like