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

OOP Unit-3 Preeti

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)
22 views

OOP Unit-3 Preeti

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/ 16

UNIT-3

Inheritance:
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-
Oriented Programming.
Inheritance is a feature or a process in which, new classes are created from the existing
classes. The new class created is called “derived class” or “child class” and the
existing class is known as the “base class” or “parent class”. The derived class now is
said to be inherited from the base class.
When we say derived class inherits the base class, it means, the derived class inherits
all the properties of the base class, without changing the properties of base class and
may add new features to its own. These new features in the derived class will not
affect the base class. The derived class is the specialized class for the base class.
• Sub Class: The class that inherits properties from another class is called
Subclass or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is
called Base Class or Superclass.

Implementing inheritance in C++: For creating a sub-class that is inherited from the
base class we have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified,
PRIVATE is taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it
does inherit a full parent object, which contains any private members which that
class declares.
Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Note:
o When a base class is privately inherited by the derived class, public members of
the base class becomes the private members of the derived class and therefore, the
public members of the base class can only be accessed by the member functions of
the derived class. They are inaccessible to the objects of the derived class.

o On the other hand, when the base class is publicly inherited by the derived class,
public members of the base class also become the public members of the derived
class. Therefore, the public members of the base class are accessible by the objects
of the derived class as well as by the member functions of the derived class.

// C++ program to demonstrate implementation of Inheritance

#include <bits/stdc++.h>
using namespace std;

// Base class
class Parent {
public:
int id_p;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent {
public:
int id_c;
};

// main function
int main()
{
Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is: " << obj1.id_c << '\n';
cout << "Parent id is: " << obj1.id_p << '\n';

return 0;
}

Output
Child id is: 7
Parent id is: 91
Output:
Child id is: 7
Parent id is: 91

Modes of Inheritance: There are 3 modes of inheritance.


1. Public Mode: If we derive a subclass 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 the derived
class.
2. Protected Mode: If we derive a subclass from a Protected base class.
Then both public members and protected members of the base class will
become protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then
both public members and protected members of the base class will become
Private in the derived class.
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Types of Inheritance in C++

1. Single Inheritance: In single inheritance, a class is allowed to inherit from only


one class. i.e. one subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};

OR

class A
{
... .. ...
};

class B: public A
{
... .. ...
};
Example:

// C++ program to explain Single inheritance


#include<iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// sub class derived from a single base classes


class Car : public Vehicle {

};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can


inherit from more than one class. i.e one subclass is inherited from more than
one base class.

Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
};

class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
// Example:

#include<iostream>
using namespace std;

class A
{
protected:
int a;

public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;

void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
protected:
int b;

public:
void set_B()
{
cout<<"Enter the Value of B=";
cin>>b;
}

void disp_B()
{
cout<<endl<<"Value of B="<<b;
}
};

class C: public B
{
int c,p;

public:
void set_C()
{
cout<<"Enter the Value of C=";
cin>>c;
}

void disp_C()
{
cout<<endl<<"Value of C="<<c;
}

void cal_product()
{
p=a*b*c;
cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;
}
};

main()
{

C c;
c.set_A();
c.set_B();
c.set_C();
c.disp_A();
c.disp_B();
c.disp_C();
c.cal_product();

return 0;

}
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from
another derived class.

Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Example: C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler()
{
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car : public fourWheeler {
public:
Car() { cout << "Car has 4 Wheels\n"; }
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is
inherited from a single base class. i.e. more than one derived class is created from a
single base class.

Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

Example: C++ program to implement Hierarchical Inheritance


#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}
6. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by
combining more than one type of inheritance. For example: Combining
Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple
inheritances:
Example: C++ program for Hybrid Inheritance

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle, public Fare {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

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.
Need for Virtual Base Classes: Consider the situation where we have one class A .
This class 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.

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. 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? One inherited through B or the
other inherited through C. This confuses compiler and it displays error.
#include <iostream>
using namespace std;

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();
}

Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note: void A::show()

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
Note:
virtual can be written before or after the public. Now only one copy of
data/function member will be copied to class C and class B and class A becomes the
virtual base class. Virtual base classes offer a way to save space and avoid
ambiguities in class hierarchies that use multiple inheritances. When a base class is
specified as a virtual base, it can act as an indirect base more than once without
duplication of its data members. A single copy of its data members is shared by all
the base classes that use virtual base.
#include <iostream>
using namespace std;

class A {
public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A {


};

class C : public virtual A {


};

class D : public B, public C {


};

int main()
{
D object; // object creation of class d
cout << "a = " << object.a << endl;

return 0;
}

Output:
a = 10

Function Overriding:
Inheritance is a feature of OOP that allows us to create derived classes from a base
class. The derived classes inherit features of the base class.
Suppose, the same function is defined in both the derived class and the based class.
Now if we call this function using the object of the derived class, the function of the
derived class is executed.
This is known as function overriding in C++. The function in derived class overrides
the function in base class.

// C++ program to demonstrate function overriding

#include <iostream>
using namespace std;

class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;
derived1.print();
return 0;
}

Output

Derived Function

Pure virtual functions are used


if a function doesn't have any use in the base class
but the function must be implemented by all its derived classes
Let's take an example,
Suppose, we have derived Triangle, Square and Circle classes from the Shape class,
and we want to calculate the area of all these shapes.
In this case, we can create a pure virtual function named calculateArea() in the Shape.
Since it's a pure virtual function, all derived classes Triangle, Square and Circle must
include the calculateArea() function with implementation.
A pure virtual function doesn't have the function body and it must end with = 0. For
example,

class Shape {
public:

// creating a pure virtual function


virtual void calculateArea() = 0;
};

Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's
just the way we define pure virtual functions.

Abstract Class
A class that contains a pure virtual function is known as an abstract class. In the above
example, the class Shape is an abstract class.
We cannot create objects of an abstract class. However, we can derive classes from
them, and use their data members and member functions (except pure virtual
functions).

// C++ program to calculate the area of a square and a circle

#include <iostream>
using namespace std;

// Abstract class
class Shape {
protected:
float dimension;

public:
void getDimension() {
cin >> dimension;
}

// pure virtual Function


virtual float calculateArea() = 0;
};

// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};

// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};

int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;

cout << "\nEnter radius of the circle: ";


circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;

return 0;
}

Output

Enter the length of the square: 4


Area of square: 16

Enter radius of the circle: 5


Area of circle: 78.5

You might also like