Inheritance and Pointers
Transcript of Inheritance and Pointers
Object Oriented Programming[210243]
SE Computer Engineering
UNIT-II
Inheritance and Pointers
By
Ms. Vaishali Khandave
Assistant Professor
Computer Engineering
Bhujbal Knowledge CityMET Institute of Engineering
10/09/2020 1
Inheritance
What is Inheritance?
10/09/2020 2
Inheritance
What is Inheritance?
In C++, inheritance is a process in which one object
acquires all the properties and behaviors of its parent
object automatically. In such way, you can reuse, extend
or modify the attributes and behaviors which are
defined in other class.
10/09/2020 3
Inheritance
10/09/2020 4
Inheritance
10/09/2020 5
Derived Class: The class that inherits properties from another class is
known as derived class, it is also known as sub class or child class.
Base Class: The class that is being inherited by derived class is known as
base class, super class or parent class.
The idea of inheritance implements the “ is a ”relationship. For instance,
dog is a animal, cat is a animal as well and so on.
Inheritance
Advantage of C++ Inheritance
Code reusability: You 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.
10/09/2020 6
Inheritance
Derived ClassesA Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
};
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base
class are publicly inherited or privately inherited. It can be public, private,
protected.
base_class_name: It is the name of the base class.
10/09/2020 7
Inheritance➢ When the base class is privately inherited by the derived class,
public members of the base class becomes the private members of
the derived class. Therefore, the public members of the base class
are not accessible by the objects of the derived class only by the
member functions of the derived class.
➢ 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 base class.
Note:
➢ In C++, the default mode of visibility is private.
➢ The private members of the base class are never inherited.
10/09/2020 8
InheritanceVisibility Modes/ Access specifiers:
10/09/2020 9
➢ Public: When the member is declared as public, it is accessible to all the
functions of the program.
➢ Private: When the member is declared as private, it is accessible within
the class only.
➢ Protected: When the member is declared as protected, it is accessible
within its own class as well as the class immediately derived from it.
InheritanceVisibility Modes / Access specifiers :
10/09/2020 10
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.
Inheritance
10/09/2020 11
Visibility of inherited members
Inheritance
10/09/2020 12
Private
public
protected
Not inheited
public
protected
Private
public
protected
Not inheited
protected
protected
Private
public
protected
Not inheited
private
private
private
inherited
public
inherited
Protected
inherited
➢ When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
➢ We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are
applied −
➢ Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the derived
class and protected members of the base class become protected members of the
derived class. A base class's private members are never accessible directly from a
derived class, but can be accessed through calls to
the public and protected members of the base class.
➢ Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class become protected members
of the derived class.
➢ Private Inheritance − When deriving from a private base
class, public and protected members of the base class become private members of
the derived class.
10/09/2020 13
Inheritance
Types Of Inheritance
C++ supports five types of inheritance:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
10/09/2020 14
Inheritance
10/09/2020 15
Single InheritanceSingle inheritance is defined as the inheritance in which a
derived class is inherited from the only one base class.
10/09/2020 16
Syntax:
class A
{
……….
……….
};
class B:public A
{
………..
………...
};
Single Inheritance#include <iostream>
using namespace std;
class Account
{
public:
float salary = 60000;
};
class Programmer: public Account
{
public:
float bonus = 5000;
};
int main()
{
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
10/09/2020 17
Single Inheritance#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};
10/09/2020 18
Single Inheritanceclass B : private A
{
public:
void display()
{
int result = mul();
cout <<"Multiplication of a and b is : "<<result<< endl;
}
};
int main()
{
B b;
b.display();
return 0;
} 10/09/2020 19
Home Assignment➢ Write a C++ program to add two numbers using single
inheritance. Accept these two numbers from the user in base
class and display the sum of these two numbers in derived class.
10/09/2020 20
Multilevel InheritanceIn C++ programming, not only you can derive a class from the
base class but you can also derive a class from the derived class.
This form of inheritance is known as multilevel inheritance
10/09/2020 21
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
class C: public B
{
... ... ...
};
Multilevel Inheritance
10/09/2020 22
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C obj;
obj.display();
return 0;
}
Multilevel Inheritance#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{
public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
10/09/2020 23
Multilevel Inheritance// sub class derived from two base classes
class Car: public fourWheeler
{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
10/09/2020 24
Home AssignmentWrite a C++ program to calculate the percentage of a student using
multi-level inheritance. Accept the personal details of student such
as roll no, name, gender in base class. A class will derived from the
above mentioned class in which accept the marks of five subjects
and includes a function to find the total marks obtained and another
class derived from this class which calculates and displays the
percentage of five student.
10/09/2020 25
Multiple InheritanceMultiple Inheritance: Multiple Inheritance is a feature of C++
where a class can inherit from more than one base classes. i.e
one sub class is inherited from more than one base classes
10/09/2020 26
class A
{
..........
};
class B
{
...........
} ;
class C
{
...........
} ;
class D: access_specifierA, access_specifier B,
access_specifier C
{
...........
} ;
Multiple Inheritance#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
}; 10/09/2020 27
Multiple Inheritanceclass C : public A, public B
{
public:
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}10/09/2020 28
marks of three subjects
Home Assignment➢ Create employee bio-data using following classes i)Personal
record ii)Professional record iii)Academic record. Assume
appropriate data members and member function to accept
required data and print bio-data using multiple inheritance.
10/09/2020 29
Hierarchical InheritanceWhen several classes are derived from common base class it is
called hierarchical inheritance.
In C++ hierarchical inheritance, the feature of the base class is
inherited onto more than one sub-class.
10/09/2020 30
class A
{
};
class B : access_specifier A
{
} ;
class C : access_specifier A
{
} ;
class D : access_specifier A
{
} ;
Hierarchical Inheritance
10/09/2020 31
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
Hierarchical Inheritance
10/09/2020 32
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
Hierarchical Inheritance
10/09/2020 33
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
cout << "Enter the length and breadth of a rectangle: " << endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
cout << "Area of the rectangle is : " <<m<< endl;
cout << "Enter the base and height of the triangle: " << endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
cout <<"Area of the triangle is : " << n<<endl;
return 0;
}
Home Assignment➢ Create a base class Person. Write accept() function to take the
data as name, gender and age and write display function() to
display the data. Then inherit Employee (Name of company,
salary) and Student (Institute, Department) classes from Person.
Use the same function name as accept() and display() in both
Employee and Student. Write a C++ program using Hierarchical
Inheritance .
10/09/2020 34
Hybrid InheritanceThe inheritance in which the derivation of a class involves more than one form
of any inheritance is called hybrid inheritance. Basically C++ hybrid
inheritance is combination of two or more types of inheritance. It can also be
called multi path inheritance
10/09/2020 35
class A
{
};
class B : public A
{
} ;
class C : public A
{
};
class D : public B, public C
{
};
Hybrid Inheritance#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
cout << "Enter the value of 'a' : " << endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : " << endl;
cin>>b;
}
};10/09/2020 36
Hybrid Inheritanceclass C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c : " << endl;
cin>>c;
}
};
class D : public B, public C
{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c<< endl;
}
};
10/09/2020 37
Hybrid Inheritance
int main()
{
D d;
d.mul();
return 0;
}
10/09/2020 38
Home AssignmentDesign the classes using following hybrid inheritance:
Define appropriate functions to accept and display the details.
Write a program to accept details of n instructors and display them.
10/09/2020 39
Virtual Base Class
10/09/2020 40
Virtual Base Class
10/09/2020 41
The child has two direct base classes – parent 1 and parent 2 which themselves
have a common base class grandparent. The child inherits the traits of
grandparent via two separate paths. All the public and protected members of
grandparent are inherited into child twice, first via parent 1 and again via
parent 2. This introduces ambiguity while accessing member inside child class
and should be avoided. This can be solved by declaring the common base class
as a virtual base class while declaring the direct base classes i.e. grand parent
class should be declared as a virtual base class while declaring parent 1 and
parent 2. Now only one copy of the members of grand parent will be inherited
into child.
Virtual Base Class
10/09/2020 42
class A // grand parent
{
...
...
};
class B : public virtual A // parent 1
{
...
...
};
class C : public virtual A // parent 2
{
...
...
};
class D : public B, public C //child
{
//only one copy of the members of A will be inherited.
...
...
};
Virtual Base Class
10/09/2020 43
#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();
return 0;
}
Virtual Base Class
10/09/2020 44
Compilation failed due to following errors:
main.cpp: In function ‘int main()’:
main.cpp:24:12: error: request for member ‘show’ is ambiguous
object.show();
^~~~
main.cpp:6:10: note: candidates are: void A::show()
void show()
^~~~
main.cpp:6:10: note: void A::show()
Virtual Base Class
10/09/2020 45
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 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.
Virtual Base Class
10/09/2020 46
#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;
}
Virtual Base Class
10/09/2020 47
Output:
a=10
Explanation :The class A has just one data member a which is public.
This class is virtually inherited in class B and class C. Now class B and
class C becomes virtual base class and no duplication of data
member a is done.
Ambiguity Resolution
10/09/2020 48
Ambiguity Resolution in Multiple Inheritance:
Ambiguity can be occurred using the multiple inheritance when a
function with the same name occurs in more than one base class.
Ambiguity Resolution
10/09/2020 49
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "SE COMPUTER" << endl;
}
};
class B
{
public:
void display()
{
cout << "STUDENTS" << endl;
}
};
class C : public A, public B
{ public:
void view()
{
display();
}
};
int main()
{
C c;
c.view();
return 0;
}
Ambiguity Resolution
10/09/2020 50
In member function 'void C::view()':
error: reference to 'display' is ambiguous
The above issue can be resolved by using the class resolution
operator with the function. In the above example, the derived
class code can be rewritten as:
class C : public A, public B
{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.
}
};
Ambiguity Resolution
10/09/2020 51
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "SE COMPUTER" << endl;
}
};
class B
{
public:
void display()
{
cout << "STUDENTS" << endl;
}
};
class C : public A, public B
{
public:
void view()
{
A::display();
B::display();
}
};
int main()
{
C c;
c.view();
return 0;
}
Output:
SE COMPUTER
STUDENTS
Ambiguity Resolution
10/09/2020 52
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "SE COMPUTER" << endl;
}
};
class B
{
public:
void display()
{
cout << "STUDENTS" << endl;
}
};
class C : public A, public B
{
public:
void display()
{
cout<<"NASHIK"<<endl;
A::display();
B::display();
}
};
int main()
{
C c;
c.display();
return 0;
}
Output:
NASHIK
SE COMPUTER
STUDENTS
Ambiguity Resolution
10/09/2020 53
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "SE COMPUTER" << endl;
}
};
class B
{
public:
void display()
{
cout << "STUDENTS" << endl;
}
};
class C : public A, public B
{
public:
void display()
{
cout<<"NASHIK"<<endl;
}
};
int main()
{
C c;
c.display();
c.A::display();
c.B::display();
return 0;
}
Output:
NASHIK
SE COMPUTER
STUDENTS
Ambiguity Resolution
10/09/2020 54
Ambiguity Resolution in Single Inheritance:
Ambiguity can be occurred using the single inheritance when a
function with the same name occurs in base class and derived
class.
Ambiguity Resolution
10/09/2020 55
#include<iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"C++"<<endl;
}
} ;
class B :public A
{
public:
void display()
{
cout<<"Object Oriented Programming"<<endl;
}
} ;
int main()
{
B b;
b.display(); // Calling the display() function of B class.
b.A :: display(); // Calling the display() function defined in A class.
b.B :: display(); // Calling the display() function defined in B class.
return 0;
}
Output:
Object Oriented Programming
C++
Object Oriented Programming
Constructor & Destructor in derived classes
10/09/2020 56
➢ A derived-class constructor :
❑Calls the constructor for its base class first to initialize its
base-class members.
❑If the derived-class constructor is omitted, its default
constructor calls the base-class’ default constructor
➢ A derived-class destructor :
❑Destructors are called in the reverse order of constructor
calls :
❑So a derived-class destructor is called before its base class
destructor
Order of calling Constructors and
Destructors in Inheritance
10/09/2020 57
Guess output ??
10/09/2020 58
class parent //parent class
{
public:
parent() //constructor
{
cout<<"Parent Constructor\n";
}
~parent() //destructor
{
cout<<"Parent Destructor\n";
}
};
class child : public parent //child class
{
public:
child() //constructor
{
cout<<"Child Constructor\n";
}
~ child() //destructor
{
cout<<"Child Destructor\n";
}
};
int main()
{
child c;
return 0;
}
Program Output
10/09/2020 59
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
Overriding Member Function
10/09/2020 60
Requirements for Overriding a Function :
➢ Inheritance should be there.
- Function overriding cannot be done within a class. For this
we require a derived class and a base class.
➢ Redefining a function in derived class is called function
overriding.
➢ Function that is redefined must have exactly same signature in
both base and derived class, that means same name, same
return type and same list of parameters but the task carried out
with it is different.
Overriding Member Function
10/09/2020 61
• Derived class object will invoke
the derived class function.
• How to access the overridden
function of the base class??
First Solution
10/09/2020 62
class base
{
public:
void getdata()
{
cout<<"base..";
}
};
class derived:public base
{
public:
void getdata()
{
cout<<"derived..";
}
};
int main()
{
derived obj;
obj.base::getdata();
obj. getdata();
return 0;
}
Invoke the base class function
using base class name and
scope resolution operator.
Second Solution
10/09/2020 63
Invoke the base class functionfrom the derived classfunction using base classname and scope resolutionoperator.
Program
10/09/2020 64
#include <iostream>
using namespace std;
class A
{
protected:
int a,b;
public:
void get()
{
a=10;
b=20;
}
void cal()
{
int c;
c=a+b;
cout<<"Addition is="<<c<<endl;
}
};
class B:public A
{
public:
void set()
{
a=40;
b=20;
}
void cal()
{
int c;
c=a-b;
cout<<"Substraction is="<<c<<endl;
}
};
int main()
{
B obj;
obj.get();
obj.A::cal();
obj.set();
obj.cal();
return 0;
}
10/09/2020 65
Nested class
10/09/2020 66
➢ When one class is defined inside the other class then it is
called as nested class.
➢ A nested class is a class which is declared in another enclosing
class.
➢ A nested class is a member and as such has the same access
rights as any other member.
➢ The members of an enclosing class have no special access to
members of a nested class.
Nested class
10/09/2020 67
#include<iostream>
using namespace std;
class A
{
public:
class B
{
private:
int num;
public:
void getdata(int n)
{
num = n;
}
void putdata()
{
cout<<"The number is "<<num;
}
};
};
int main()
{
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
Output is:
Nested classes in C++
The number is 9
Friend class
10/09/2020 68
Refer UNIT I