0% found this document useful (0 votes)
26 views

EC104 - Unit 8

The document discusses different types of inheritance in object-oriented programming. It explains single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance. Examples are provided for each type of inheritance to demonstrate how a derived class inherits from a base class.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

EC104 - Unit 8

The document discusses different types of inheritance in object-oriented programming. It explains single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance. Examples are provided for each type of inheritance to demonstrate how a derived class inherits from a base class.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit 8

Inheritance: Extending classes


• Re-accessability is yet another feature of OOP's. C++ strongly
supports the concept of reusability.
• The C++ classes can be used again in several ways. Once a class has
been written and tested, it can be adopted by another programmers.
• This is basically created by defining the new classes, reusing the
properties of existing ones.
• The mechanism of deriving a new class from an old one is called
'INHERTANCE'.
• The capability of a class to derive properties and characteristics from
another class is called Inheritance.
• The old class is called 'BASE‘ (parent) class and the new one is called
'DERIEVED‘ (child) class.
• Why and when to use inheritance?
• Modes of Inheritance
• Types of Inheritance
Why and when to use inheritance?
• Consider a group of vehicles. You need to create classes for Bus, Car
and Truck. The methods fuelAmount(), capacity(), applyBrakes() will
be same for all of the three classes. If we create these classes avoiding
inheritance then we have to write all of these functions in each of the
three classes as shown in below figure:
Using inheritance, we have to write the functions only one time
instead of three times as we have inherited rest of the three
classes from base class(Vehicle).
Defining Derived Classes
• A derived class is specified by defining its relationship with the base
class in addition to its own details.
• The general syntax of defining a derived class is as follows:

class d_classname : Access specifier baseclass_name


{ __
__ // members of derived class
};
• The colon(:) indicates that the a-class name is derived from the base
class name.
• The access specifier or the visibility mode is optional and, if present,
may be public, private or protected.
• By default it is private. Visibility mode describes the status of derived
features e.g.
// C++ program to demonstrate implementation of
Inheritance
#include <iostream>
using namespace std;
//Base class
class Parent
{ public:
int id_p; OUTPUT:
}; Child id is 7
// Sub class inheriting from Base Class(Parent) Parent id is 91
class Child : public Parent
{ public:
int id_c; };
//main function
int main()
{ Child obj1;
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then
both public member and protected members of the base class will become
protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both
public member and protected members of the base class will become Private
in derived class.
Note : The private members in the base class cannot be directly accessed in the
derived class, while protected members can be directly accessed.
// C++ Implementation to show that a derived class // doesn’t inherit access to private data
members. // However, it does inherit a full parent object.
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public // y is protected // z is not accessible from B
};

class C : protected A { // x is protected // y is protected


// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private // y is private // z is not accessible from D};
Types Of Inheritance:-
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance
1. Single Inheritance
Class A Parent/Base Class

Class B Child/Derived Class

class subclass_name : access_mode


base_class
{
// body of subclass
};
// C++ program to explain Single inheritance
#include<iostream>
using namespace std;
class Vehicle { // base class
public: Vehicle()
{
cout << "This is a Vehicle\n";
}
}; OUTPUT:
// sub class derived from a single base classes
This is a Vehicle
class Car : public Vehicle {
};

int main() // main function


{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
// Example: public:
void set_B()
#include<iostream> { set_A();
using namespace std; cout<<"Enter the Value of B=";
cin>>b;
class A }
{ void disp_B()
protected: {
int a; disp_A();
public: cout<<endl<<"Value of B="<<b;
void set_A() }
{ void cal_product()
cout<<"Enter the Value of A="; { p=a*b;
cin>>a; cout<<endl<<"Product of "<<a<<" * "<<b<<" Output:-
} = "<<p; Enter the Value of A= 3
void disp_A() } Value of A=3
{ }; Enter the Value of B= 5
cout<<endl<<"Value of A="<<a; main() Value of B= 5
} { Product of 3 * 5 = 15
}; B b;
class B: public A b.set_B();
{ b.cal_product();
int b,p; return 0;}
2. Multiple Inheritance

Class A Class B Bass Class


Bass Class

Class C Derived Class


class subclass_name : access_mode base_class1, access_mode base_class2, ...
{
// body of subclass
};
class B
{ ... .. ...
};
class C
{... .. ...
};
class A: public B, public C
{
... ... ...
};
3. Multilevel Inheritance class A
{
Class A ... .. ...
};
Bass Class class B:public A
{
... .. ...
Class B Derived Class };
class C: public B
{
... ... ...
Class C };
class A
{

4. Hierarchical Inheritance }
// body of the class A.

class B : public A
{

Class A
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public B
{
// body of class D.
}
Class B Class C

Class D Class E Class F Class G


5. Hybrid Inheritance
Class A Class F

Class B Class C

Class D Class E Class G


5. Hybrid Inheritance(Special case)
Class A

Class B Class C

Class D Class E Class G


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.
// C++ program demonstrating ambiguity in int main()
Multipath {
// Inheritance
#include <iostream> ClassD obj;
using namespace std;
// obj.a = 10; // Statement 1, Error
class ClassA { // obj.a = 100; // Statement 2, Error
public:
int a; obj.ClassB::a = 10; // Statement 3
}; obj.ClassC::a = 100; // Statement 4
class ClassB : public ClassA {
public: obj.b = 20;
int b; obj.c = 30;
}; obj.d = 40;
class ClassC : public ClassA {
public: cout << " a from ClassB : " << obj.ClassB::a;
int c; cout << "\n a from ClassC : " <<
}; obj.ClassC::a;
class ClassD : public ClassB, public ClassC {
public: cout << "\n b : " << obj.b;
int d; cout << "\n c : " << obj.c;
}; cout << "\n d : " << obj.d << '\n';}
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.
• There are 2 Ways to Avoid this Ambiguity:

1) Avoiding ambiguity using the scope resolution operator: Using the


scope resolution operator we can manually specify the path from which
data member a will be accessed.
2) Avoiding ambiguity using the virtual base class:
#include<iostream>
class ClassA
{
public: int main()
int a; {
}; ClassD obj;
class ClassB : virtual public ClassA
{ obj.a = 10; // Statement 3
public: obj.a = 100; // Statement 4
int b;
}; obj.b = 20;
class ClassC : virtual public ClassA obj.c = 30;
{ obj.d = 40;
public:
int c; cout << "\n a : " << obj.a;
}; cout << "\n b : " << obj.b;
class ClassD : public ClassB, public ClassC cout << "\n c : " << obj.c;
{ cout << "\n d : " << obj.d << '\n';
public: }
int d;
};
Virtual base class in C++
• 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.
• Need for Virtual Base Classes: Consider the situation where we have
one class A .This class is A is inherited by two other classes B and
C. Both these class are inherited into another in a new class D as
shown in figure below.
Virtual Function in C++
• A virtual function (also known as virtual methods) is a member function that
is declared within a base class and is re-defined (overridden) by a derived
class.
• When you refer to a derived class object using a pointer or a reference to the
base class, you can call a virtual function for that object and execute the
derived class’s version of the method.
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
• They are mainly used to achieve Runtime polymorphism.
• Functions are declared with a virtual keyword in a base class.
• The resolving of a function call is done at runtime.
Rules for Virtual Functions

• The rules for the virtual functions in C++ are as follows:


• Virtual functions cannot be static.
• A virtual function can be a friend function of another class.
• Virtual functions should be accessed using a pointer or reference of base class
type to achieve runtime polymorphism.
• The prototype of virtual functions should be the same in the base as well as the
derived class.
• They are always defined in the base class and overridden in a derived class. It is
not mandatory for the derived class to override (or re-define the virtual function),
in that case, the base class version of the function is used.
• A class may have a virtual destructor but it cannot have a virtual constructor.
// C++ program to illustrate
// concept of Virtual Functions int main()
{
#include <iostream> base* bptr;
using namespace std; derived d;
bptr = &d;
class base {
public: // Virtual function, binded at runtime
virtual void print() { cout << "print base class\ bptr->print();
n"; }
// Non-virtual function, binded at compile time
void show() { cout << "show base class\n"; } bptr->show();
};
return 0;
class derived : public base { }
public:
void print() { cout << "print derived class\n"; }
print derived class
void show() { cout << "show derived class\n"; } show base class

};
Abstract classes
• An abstract class is one that is not used to create objects.
• An abstract class is designed only to act as base class.

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


Constructors in derived classes
• We can use constructors in derived classes in C++.
• If the base class constructor does not have any arguments,
there is no need for any constructor in the derived class.
• But if there are one or more arguments in the base class
constructor, derived class need to pass argument to the base
class constructor.
• If both base and derived classes have constructors, base
class constructor is executed first.
• In the case of Multiple inheritance, the base classes are constructed in
the order in which they appear in the declaration derived class.
• In the case of Multilevel inheritance, the constructors will be
executed in the order of inheritance.
:
Example:

D(int a1, int a2, float b1, float b2, int d1):
A(a1,a2), // call to Constructor A
B(b1,b2) // call to Constructor B

{
d=d1;
}
Method of inheritance
Order of Execution
class B:public A
A(); base constructor
{
B(); derived constructor
};
A(); base constructor(first base)
class B:public A, public C
C(); derived constructor(base two)
{
B(); derived constructor
};
C(); virtual base
class B:public A, virtual public C
A(); base constructor
{
B(); derived constructor
};
#include<iostream> class gamma: public beta, public alpha
{
using namespace std;
int m,n;
class alpha public:
{ int x; gamma(int a, float b, int c, int d):
public: alpha(a), beta(b)
alpha(int i) {
{ x=i; m=c;
cout<<“alpha initialized\n”; } n=d;
void show_x(void) cout<<“gamma initialized\
{ cout<<“X=“<<x<<“\n”; } n”; }

void show_mn(void)
class beta { cout<<“m=“<<m<<“\n”;
{ float y; Output:
cout<<“n=“<<n<<“\n”; }
public:
beta initialized
beta(float j) };
alpha initialized
{ Int main()
gamma initialized
y=j; {
X=5
cout<<“beta initialized\n”; } gamma g(5,10.75, 20 , 30);
Y=10.75
cout << “\n”;
m=20
g.show_x();
void show_y(void) n=30
g.show_y();
{ g.show_mn();
cout<<“Y=“<<y<<“\n”; } };

You might also like