2. What Is Inheritance?
• Provides a way to create a new class from an existing class
• The new class is a specialized version of the existing class
• It makes it easier to create and maintain an application.
• It provides an opportunity to reuse the code functionality and fast
implementation time.
• Syntax:
class derived-class_name : visivility-mode base-class_name
{ . . . . // members of the derived class . . . . };
4. The "is a" Relationship
• Inheritance establishes an "is a" relationship between classes.
– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
5. Inheritance – Terminology and Notation in C++
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};
6. Example:
#include<iostream>
using namespace std;
class Person {
int id;
char name[100];
public:
void set_p() {
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
//or cin.ignore();
cout<<"Enter the Name:";
cin.get(name,100);
}
void display_p()
{
cout<<endl<<id<<"t"<<name;
} };
class Student: private Person
{
char course[50];
int fee;
public:
void set_s()
{
set_p();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}
8. What Does a Child Have?
An object of the derived
class has:
• all members defined
in child class
• all members declared
in parent class
An object of the derived
class can use:
• all public members
defined in child class
• all public members
defined in parent
class
9. Protected Members and Class Access
• protected member access specification: like private,
but accessible by objects of derived class
• Class access specification: determines how private,
protected, and public members of base class are
inherited by the derived class
10. Class Access Specifiers
1) public – object of derived class can be treated as
object of base class (not vice-versa)
2) protected – more restrictive than public, but allows
derived classes to know details of parents
3) private – prevents objects of derived class from
being treated as objects of base class.
12. Inheritance vs. Access
private: x
protected: y
public: z
private: x
protected: y
public: z
private: x
protected: y
public: z
Base class members
x is inaccessible
private: y
private: z
x is inaccessible
protected: y
protected: z
x is inaccessible
protected: y
public: z
How inherited base class
members
appear in derived class
private
base class
protected
base class
public
base class
13. Inheritance vs. Access Public
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
class Test : public Grade
When Test class inherits
from Grade class using
public class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
void setScore(float);
float getScore();
char getLetter();
14. Inheritance vs. Access Protected
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
protected class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
protected members:
void setScore(float);
float getScore();
float getLetter();
class Test : protected Grade
15. Inheritance vs. Access Private
private members:
int numQuestions:
float pointsEach;
int numMissed;
void setScore(float);
float getScore();
float getLetter();
public members:
Test(int, int);
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
private class access, it
looks like this:
class Test : private Grade
16. Example 2
#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
{
int b, p;
public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}
void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}
18. Forms of Inheritance
•Single Inheritance
•Multiple Inheritance
•Hierarchical Inheritance
•Multilevel Inheritance
•Hybrid Inheritance (also known as Virtual Inheritance)
20. Multilevel Inheritance
class derive1 : public base // derived class from base class
{
protected:
int y;
public:
void readdata()
{
cout << "nEnter value of y= "; cin >> y;
}
};
21. Multilevel Inheritance
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "nEnter value of z= "; cin >> z;
}
void product()
{
cout << "nProduct= " << x * y * z;
} };
22. Multilevel Inheritance
int main( )
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
}
OUTPUT:
Enter value of x= 2
Enter value of y= 4
Enter value of z= 5
Product= 40
23. Hierarchical Inheritance
#include <iostream>
using namespace std;
class A // Base class
{
Protected:
int x, y; // data members
public:
void getdata() // to input x and y
{
cout<< "Enter value of x and y:n";
cin>> x >> y;
}
};
24. Hierarchical Inheritance
class B : public A //B is derived from class base
{
public:
void product()
{
cout<< "nProduct= " << x * y <<endl;
} };
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout<< "nSum= " << x + y; // Perform sum
} };
25. Hierarchical Inheritance
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}
OUTPUT:
Enter value of x and y:
2 4
Product= 8
Enter value of x and y:
2 4
Sum= 6
26. Multiple Inheritance
#include <iostream>
using namespace std;
class stud {
protected:
int roll, m1, m2;
public:
void get()
{
cout << "Enter the Roll No.: ";
cin >> roll;
cout << "Enter the two highest marks: ";
cin >> m1 >> m2;
}
};
28. Multiple Inheritance
class output : public stud, public extracurriculam {
int tot, avg;
public:
void display()
{
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "nntRoll No : " << roll << "ntTotal : " << tot;
cout << "ntAverage : " << avg;
} };
int main()
{
output O;
O.get();
O.getsm();
O.display(); }
OUTPUT:
Enter the Roll No.: 2
Enter the two highest marks: 34 56
Enter the mark for Extra Curriculam Activities: 5
Roll No : 2
Total : 95
Average : 31
29. MultPath Inheritance
#include <iostream>
using namespace std;
class person {
protected:
char name[100];
int code;
public:
void input()
{
cout<<"nEnter the name of the person : ";
cin>>name;
cout<<endl<<"Enter the code of the person : ";
cin>>code; }
void display()
{
cout<<endl<<"Name of the person : "<<name;
cout<<endl<<"Code of the person : "<<code; } };
30. MultiPath Inheritance
class account:virtual public person
{
protected:
float pay;
public:
void getpay()
{
cout<<endl<<"Enter the pay : ";
cin>>pay;
}
void display()
{
cout<<endl<<"Pay : "<<pay; } };
31. MultiPath Inheritance
class admin:virtual public person
{
Protected:
int experience;
public:
void getexp()
{
cout<<endl<<"Enter the experience : ";
cin>>experience;
}
void display()
{
cout<<endl<<"Experience : "<<experience; } };
32. MultiPath Inheritance
class master: public account, public admin
{
char n[100];
public:
void gettotal()
{
cout<<endl<<"Enter the company name : ";
cin>>n;
}
void display()
{
cout<<endl<<"Company name : "<<n;
}
};
33. MultiPath Inheritance
int main()
{
master m1;
m1.input();
m1.getpay();
m1.getexp();
m1.gettotal();
m1.person::display();
m1.account::display();
m1.admin::display();
m1.display();
return 0;
}
OUTPUT:
Enter the name of the person : PPPP
Enter the code of the person : 09
Enter the pay : 80000
Enter the experience : 15
Enter the company name : UMIT
Name of the person : PPPP
Code of the person : 9
Pay : 80000
Experience : 15
Company name : UMIT
34. CS1 -- Inheritance and Polymorphism 34
What to inherit?
• In principle, every member of a base class
is inherited by a derived class
– just with different access permission
• However, there are exceptions for
– constructor and destructor
– operator=() member
– friends
Since all these functions are class-specific
35. Constructors and Destructors in Base and
Derived Classes
• Derived classes can have their own constructors and
destructors
• When an object of a derived class is created, the base
class’s constructor is executed first, followed by the
derived class’s constructor
• When an object of a derived class is destroyed, its
destructor is called first, then that of the base class
36. Constructor Rules for Derived Classes
The default constructor and the destructor of
the base class are always called when a new
object of a derived class is created or destroyed.
class A {
public:
A ( )
{cout<< “A:default”<<endl;}
A (int a)
{cout<<“A:parameter”<<endl;}
};
class B : public A
{
public:
B (int a)
{cout<<“B”<<endl;}
};
B test(1);
A:default
B
output:
37. Constructors and Destructors in Base and
Derived Classes
#include<iostream>
using namespace std;
class BC
{
public:
BC()
{
cout<<"Base Class Constructor"<<endl;
}
~BC()
{
cout<<"Base Class Distructor"<<endl;
}
};
38. Constructors and Destructors in Base and
Derived Classes
class Derv:public BC
{
public:
Derv()
{
cout<<"Derived Class Constructor"<<endl;
}
~Derv()
{
cout<<"Derived Class Distructor"<<endl;
} };
int main()
{
Derv ob1;
cout<<"Program is ending"<<endl;
return 0;
}
39. Passing Arguments to Base Class Constructor
• Allows selection between multiple base class
constructors
• Specify arguments to base constructor on derived
constructor heading:
Square::Square(int side): Rectangle(side, side)
• Can also be done with inline constructors
• Must be done if base class has no default
constructor
40. Constructor Rules for Derived Classes
You can also specify an constructor of the base
class other than the default constructor
class A {
public:
A ( )
{cout<< “A:default”<<endl;}
A (int a)
{cout<<“A:parameter”<<endl;}
};
class C : public A {
public:
C (int a) : A(a)
{cout<<“C”<<endl;}
};
C test(1);
A:parameter
C
output:
DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )
{ DerivedClass constructor body }
41. Passing Arguments to
Base Class Constructor
Square::Square(int side):Rectangle(side,side)
derived class constructor base class constructor
derived constructor
parameter
base constructor
parameters
42. Example:
// C++ program to show how to call parameterized Constructor
// of base class when derived class's Constructor is called
#include <iostream>
using namespace std;
class Parent {
int x;
public:
Parent(int i)
{
x = i;
cout << "Inside base class's parameterized "
"constructor“ << endl; } };
43. Example:
class Child : public Parent {
public:
Child(int x): Parent(x)
{
cout << "Inside sub class's
parameterized
constructor“ << endl;
}
};
int main()
{
Child obj1(10);
return 0; }
OUTPUT:
Inside base class's
parameterized constructor
Inside sub class's
parameterized constructor
44. Constructor in Multiple Inheritance in
C++
// C++ program to show the order of constructor calls in Multiple
Inheritance
#include <iostream>
using namespace std;
// first base class
class Parent1
{
public:
// first base class's Constructor
Parent1()
{
cout << "Inside first base class" << endl;
}};
45. Constructor in Multiple Inheritance in
C++
// second base class
class Parent2
{
public:
// second base class's Constructor
Parent2()
{
cout << "Inside second base class" << endl;
}
};
46. Constructor in Multiple Inheritance in
C++
// child class inherits Parent1 and Parent2
class Child : public Parent2, public Parent1
{
public:
// child class's Constructor
Child()
{
cout << "Inside child class" << endl;
}
};
int main() {
Child obj1;
return 0;
}
OUTPUT:
Inside second base class
Inside first base class
Inside child class
47. Constructor in Multiple Inheritance :Virtual
#include<iostream>
using namespace std;
class A1
{
public:
A1()
{
cout << "Constructor of the base class A1 n";
} };
class A2
{
public:
48. A2()
{
cout << "Constructor of the base class A2 n";
}
};
class S: public A1, virtual A2
{
public:
S(): A1(), A2()
{
cout << "Constructor of the derived class S n";
}
};
// Driver code
int main()
{
S obj;
return 0;
}
OUTPUT:
Constructor of the base class A2
Constructor of the base class A1
Constructor of the derived class S
Constructor in Multiple Inheritance :Virtual
49. Order of Constructor Invocation in Derived Class
CS1 -- Inheritance and Polymorphism
50. Object Composition and Delegation
#include <iostream>
using namespace std;
class A {
public:
int x;
// Constructor initializing the data members
A() { x = 0; }
A(int a)
{
cout << "Constructor A(int a) is invoked" << endl;
x = a;
} };
51. Object Composition and Delegation
class B {
int data;
A objA;
public:
B(int a) : objA(a)
{
data = a; }
void display()
{
cout << "Data in object of class B = " << data << endl;
cout << "Data in member object of “ << "class A & B = " <<
objA.x;
} };
52. Object Composition and Delegation
// Driver code
int main()
{
// Creating object of class B
B objb(25);
// Invoking display function
objb.display();
return 0;
}
OUTPUT:
Constructor A(int a) is invoked
Data in object of class B = 25
Data in member object of class A
in class B = 25
53. Object Composition and Delegation
#include <iostream>
using namespace std;
class First {
public:
void print() { cout << "The Delegate"; }
};
class Second {
// Creating instance of the class
First ob;
public:
void print() { ob.print(); }
};
54. Object Composition and Delegation
// Driver Code
int main()
{
Second ob1;
ob1.print();
return 0;
}
OUTPUT:
The Delegate
56. Problem with Redefining Function in
Child Class
BaseClass
DerivedClass
void X();
void Y();
void Y();
DerivedClass D;
D.X();
Object D invokes function X()
In BaseClass in BaseClass,
not function Y() in DerivedClass,
because function calls are bound at
compile time.
This is static binding.
58. Late Binding
class derived : public base {
public:
void print()
{
cout << "print derived classn";
}
void show()
{
cout << "show derived classn";
}
};
59. Late Binding
int main()
{
base *bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
OUTPUT:
print derived class
show base class
60. Rules for Virtual Functions
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference
of base class type to achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the
base as well as derived class.
5. 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.
6. A class may have virtual destructor but it cannot have a virtual
constructor.
62. class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}
Pure Virtual Function
63. Abstract Class with Constructor
#include<iostream>
using namespace std;
// An abstract class with constructor
class Base
{
protected:
int x;
public:
virtual void fun() = 0;
Base(int i) {
x = i;
cout<<"Constructor of base calledn";
} };
64. class Derived: public Base
{
int y;
public:
Derived(int i, int j):Base(i) { y = j; }
void fun() { cout << "x = " << x << ", y = " << y<<'n'; }
};
Abstract Class with Constructor
65. int main(void)
{
Derived d(4, 5);
d.fun();
//object creation using pointer of base class
Base *ptr=new Derived(6,7);
ptr->fun();
return 0;
}
Abstract Class with Constructor
OUTPUT:
Constructor of base
called
x = 4, y = 5
Constructor of base
called
x = 6, y = 7
66. Virtual Destructors
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing basen";
}
virtual ~base()
{ cout << "Destructing basen";
}
};
class derived : public base {
public:
derived()
{
cout << "Constructing
derivedn"; }
virtual ~derived()
{
cout << "Destructing
derivedn"; }
};
67. Virtual Destructors
int main()
{
derived *d = new derived();
base *b = d;
delete b;
return 0;
}
OUTPUT:
Constructing base
Constructing derived
Destructing derived
Destructing base
68. Generic Programming
Class and Function Templates
An abstract recipe for producing concrete code.
Reference:
https://techvidvan.com/tutorials/cpp-templates/
69. Function Overloading
function overloading allows the same function to act on different argument
types:
int max(int a, int b) {
if (a > b) return a;
else return b;
}
float max(float x, float y) {
if (x > y) return x;
else return y;
}
This is useful, but we are duplicating code!
70. 70
The use of the word class here means
“any type”
Templates let us write the two functions with no duplication:
template <class T>
T max(T x, T y) {
if (x > y) return x;
else return y;
}
The compiler generates code for us when it comes across statements
such as:
i = max(j, k);
Template parameters are place
holders for types and classes.
For each call, the compiler generates the
complete function, replacing the type
parameter with the type or class to
which the arguments belong.
Type parameter
Function Template
71. Function Template
#include <iostream>
using namespace std;
template <class T>
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.5, 7.7) << endl; // call myMax double
cout << myMax<char>('g', 'e’) << endl; // call myMax for char
return 0; }
72. It also works for user defined types:
Date d1,d2,d3;
d3 = max(d1,d2);
Provided that as we have an operator> for the Date class.
Function templates can themselves be overloaded:
template <class T, class S>
T max(T x, S y) {
if (x > y) return x;
else return y;
}
We can now compare an object with any other
object as long as >is defined.
In fact this version can replace the previous one
(it is the special case when S = T)
Function Template
75. • Function templates are a direct generalization of function
overloading.
• Function templates share source code among structurally
similar families of functions.
• Templates can also be used with classes.
• We can create generic classes that handle different types
of data.
Function Template
76. Class Templates
• Templates are instantiated at compile time, and so, values passed
to non-type parameters must be constants.
• Class templates are sometimes called parameterized types.
• Instantiating templates is one of its major features of c++ and
one that distinguishes it from most other programming
languages.
• As a mechanism for code generation, it allows for substantial
improvements in programming efficiency.
Like function templates, a class template may have several type parameters.
Moreover, some of them may be ordinary non-type parameters.
template <class T, int n, class U, class V>
Non-type parameter
77. Class Template Ex.1
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T* ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
78. Class Template
template <typename T>
Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i); cout << endl; }
80. template<class T, int n>
class X {};
int main()
{
X<float, 22> x1; //OK
const int n=44;
X<char, n> x2; //OK
int m=66;
X<short, m> x3; //error! – m must be a constant
}
Non-type parameter
Class Templates with Non Type Parameter
81. Example Addition:
#include <iostream>
using namespace std;
template<class T>
class Add
{
T n1 = 6;
T n2 = 1;
public:
void addition()
{
cout << "n1+n2: " << n1+n2<<endl;
}
};
int main()
{
Add<int> data;
data.addition();
return 0;
}
82. The square function in this example would be handled in the
same way.
template<class T>
class X{
T square(T t) { return t*t; }
};
Member functions of a class template are themselves function
templates with the same template header as their class.
template<class T>
T square(T t) { return t*t; }
Template function
Member function of a
class Template
Class Templates and Member Function
Instantiating Class templates
83. It is instantiated by the compiler, replacing the template parameter T with the type passed
to it.
X<short> x;
Consider the class declaration:
Class X_short{
short square(short t) {return
t*t;}
};
X_short x;
Except that your compiler might
assign a different name for the class
other than X_short.
Therefore, the compiler generates the following class and object
*
Class Templates Working
84. For the Vector class - we may want Vectors of integer, float, Date, etc. Without
templates, we have to create different vectors for each of them, with templates we
can create a single generic vector:
template <class T>
class Vector {
public:
Vector(int n=100); //constructor
T& operator[](int i); //range checked!
Vector<T>& operator=(Vector<T> &v);
private:
T* p;
int size;
};
Class Templates Example:
89. int main()
{
Calculator<int> Calc1(25, 12);
Calculator<float> Calc2(13.6, 5.9);
cout << "Integer results for 25 and 12:" << endl;
Calc1.show();
cout << endl << "Float results for 13.6 and 5.9:" << endl;
Calc2.show();
return 0;
}
OUTPUT:
Integer results for 25 and 12:
Addition is: 25+12= 37
Subtraction is: 25-12= 13
Product is: 25*12= 300
Division is: 25/12= 2
Float results for 13.6 and 5.9:
Addition is: 13.6+5.9= 19.5
Subtraction is: 13.6-5.9= 7.7
Product is: 13.6*5.9= 80.24
Division is: 13.6/5.9= 2.30508
Example Calculator: