MODULE 4
Overloading, Templates and Inheritance
Introduction and Need of Operator Overloading
Operator Function
1. Member operator function
2. Non Member operator function
Overloading using Member Operator Function
Syntax of an operator function
return-type operator OP(argument list);
Where OP -> operator to be overloaded.
Type of Operator | No. of Arguments |
Unary | 0 |
Binary | 1 |
return-type class-name :: operator OP(argument list)
{
Operations that overloaded operator performs
}
Overloading Unary Operators using Member Operator Function
Member operator function takes no parameter for unary operator and is implicitly passed through “this” pointer.
Program
Write a program in C++ to overload unary minus(-).
Solution :
#include<iostream> using namespace std ; class Example { int x,y,z; public:
Example(int p,int q,int r) { x=p; y=q; z=r; } void display() { cout<<x<<” ”<<y<<” ”<<z; } void operator-() { x=-x; y=-y; z=-z; } }; int main() { Example obj (10,-20,30); cout<<”Original numbers are” obj.display(); - obj; obj.display(); return 0; } |
//Defines class Example
//Parameterized constructor
// Step 1 Operator function to overload minus
// Step 2 Invokes operator function
cout<<”Numbers after applying unary minus” |
Explanation
void operator-() { x=-x; y=-y; z=-z; } | //Operator function to overload minus
|
- obj; cout<<”Numbers after applying unary minus” | //Invokes operator function |
Output
Original numbers are
10 -20 30
Numbers after applying unary minus
-10 20 -30
Overloading ++ and – –
Overloading Prefix versions
Prefix increment
Return-type operator ++()
{
//Body of operator function
}
Example
void operator++()
{
---
}
Prefix decrement
Return-type operator --()
{
//Body of operator function
}
Example
void operator--()
{
---
}
Postfix versions
Post Increment
Return-type operator ++(int x)
{
//Body of operator function
}
where x is zero.
Example
void operator ++(int x)
{
---
}
Post Decrement
Return-type operator --(int x)
{
//Body of operator function
}
Example
void operator--(int x)
{
---
}
Program
Write a C++ program to overload ++,-- (postfix and prefix versions), !
(logical not) operator.
#include<iostream> using namespace std ; class Example int a,b; public: void accept() { cout<<”enter values of and b”; cin>>a>>b; } void display() { cout<<a<<” ”<<b<<” ”; } void operator++(); void operator--(); void operator++(int x); void operator--(int x); void operator!(); }; void Example:: operator++() { a=++a; b=++b; } void Example:: operator--() { a=--a; b=--b; } void Example:: operator++(int x) { a=a++; b=b++; } void Example:: operator--(int x) { a=a--; b=b--; } void Example:: operator!() { a=!a; b=!b; } int main() { Example O; obj.accept(); ++ O; obj.display(); obj ++; obj.display(); -- obj; obj.display(); obj --; obj.display(); ! obj; obj.display(); return 0; } |
//overloads prefix ++ //overloads prefix -- //overloads postfix ++ //overloads postfix -- //overloads logical not
//Defines operator function to overload prefix version of ++
//Defines operator function to overload prefix version of --
//Defines operator function to overload postfix version of ++
//Defines operator function to overload postfix version of --
//Defines operator function to overload logical not
//Invokes operator Functions to perform ++ --(postfix and prefix)and ‘!’ on object ‘obj’. |
Overloading Binary Operators using Member Operator Function
Program
Write a C++ program to overload binary +, - .
#include<iostream> using namespace std ; class Example { int a,b; public: Example(int p, int q) { a=p; b=q; } void display() { cout<<a<<” ”<<b<<endl; } Example operator+(Example X); Example operator-(Example X); }; Example Example::operator+(Example X) { Example E; E.a= a+X.a; E.b= b+X.b; return E } Example Example:: operator-(Example X) { Example F; F.a= a-X.a; F.b= b-X.b; return F } int main() { Example obj1(10,20); Example obj2(5,5); Example obj3(0,0); cout<<”Addition is” obj3= obj1+ obj2; obj3.display(); cout<<”Subtraction is” obj3= obj1- obj2; obj3.display(); return 0 ; } |
// Step 1 overloads + // Step 1 overloads -
// Step 2 Defines operator function to overload +
//Defines operator function to overload -
// Step 3 //Invokes overloaded binary +
// Step4 //Invokes overloaded binary -
|
Explanation
Return type of an object is always a class so it is declared as follows
Example operator+(Example X); Example operator-(Example X); | //overloads + //overloads - |
Example Example:: operator+(Example X) { Example E; E.a= a+X.a; E.b= b+X.b; return E; } Example Example:: operator-(Example X) { Example F; F.a= a-X.a; F.b= b-X.b; return F;
} | //Defines operator function to overload +
//Defines operator function to overload -
|
step 3.
O3= O1+ O2;
| //Invokes overloaded binary + |
O3= O1- O2; | //Invokes overloaded binary - |
Thus the output will be :
Output
cout<<”Addition is”
a 15 b 25
cout<<”Subtraction is”
a 5 b 15
Program
Write C++ program to demonstrate use of binary (“+”) operator overloading to add two complex numbers using member function.
#include<iostream> using namespace std ; class Demo { int real,imag; public: Demo(int p, int q) { real=p; imag=q; } void display() { cout<<real<<” +j”<<imag<<endl; } Demo operator+(Demo X); }; Demo Demo::operator+(Demo X) { Demo D; D.real=real+X.real; D.imag=imag+D.imag; return D } int main() { Demo obj1(10,20); Demo obj2(5,5); Demo obj3(0,0); cout<<”Addition is” obj3= obj1+ obj2; obj3.display(); return 0 ; } |
//……1overloads +
//.2 Defines operator function to overload +
//Defines operator function to overload -
//…..3 //Invokes overloaded binary +
|
Operator Overloading using Friend Function
Example
friend void operator-(Example &O);
Program
Write a program to overload unary –, ++,--(prefix versions) using friend function.
#include<iostream> using namespace std ; class Example { int x,y,z; public: Example(int p,int q,int r) { x=p; y=q; z=r; } void display() { cout<<x<<” ”<<y<<” ”<<z; } friend void operator-(Example &O); friend void operator++(Example &O); friend void operator--(Example &O); }; void operator-(Example & O) { O.x=-O.x; O.y=-O.y; O.z=-O.z;
} void operator++(Example & O) { O.x=O.x++; O.y=O.y++; O.z=O.z++; }
void operator--(Example & O) { O.x=O.x--; O.y=O.y--; O.z=O.z--; } }; int main() { Example O(10,-20,30); cout<<”Original numbers are”; O.display(); - O; cout<<”Numbers after applying unary minus”; O.display(); ++ O; cout<<”Numbers after applying ++”; O.display(); -- O; cout<<”Numbers after applying --”; O.display(); return 0 ; } |
//Defines class Example
//Parameterized constructor
//Operator functions to overload
//Invokes operator function for –
//Invokes operator function for ++
//Invokes operator function for -- |
Explanation
#include<iostream> using namespace std ; class Point { int x,y; public: Point() {} Point(int p, int q) { x=p; y=q; }
void display() { cout<<x<<” ”<<y<<endl; } friend Point operator+(Point P1,Point P2); friend Point operator-(Point P1,Point P2); }; Point operator+(Point P1,Point P2) { Point E; E.x= P1.x+P2.x; E.y= P1.y+P2.y; return E; } Point operator-(Point P1,Point P2) { Point E; E.x= P1.x-P2.x; E.y= P1.y-P2.y; return E; } int main() { Example obj1(10,20); Example obj2(5,5); Example obj3(0,0); obj3= obj1+ obj2; obj3.display(); obj3= obj1- obj2; obj3.display(); return 0; } |
//Step 1 overloads + using friend
// Step 2 overloads – using friend //Defines operator function to overload +
//Defines operator function to overload -
//Invokes overloaded binary +
//Invokes overloaded binary - |
Explanation
friend Point operator+(Point P1,Point P2); friend Point operator-(Point P1,Point P2); | //overloads + using friend //overloads – using friend
|
1. () Function call operator
2. = Assignment operator
3. [] subscripting operator
4. -> class member access operator
Type of operator Type of operator function | Unary | Binary |
Member Function | 0 | 1 |
Friend Function | 1 | 2 |
Program
Write a C++ program to add the complex numbers using friend function.
#include<iostream> using namespace std ; class Example { int real, imag; public: Example(int p, int q) { real=p; imag=q; } void display() { cout<<real<<“”<<imag<<endl; } friend Example operator+(Example X1,Example X2); }; Example operator+(Example X1, Example X2) { Example E; E.real= X1.real+X2.real; E.imag= X1.imag+X2.imag; return E; } int main() { Example obj1(10,20); Example obj2(5,5); Example obj3(0,0); cout<<“Addition is” obj3= obj1+ obj2; obj 3.display(); return 0; } |
//Defines operator function to overload+
//Invokes overloaded binary+
|
Program
Write a C++ program to subtract 2 complex numbers using concept of overloading using friends function.
Solution :
#include<iostream> using namespace std ; class Example { int real, imag; public: Example(int p, int q) { real=p; imag=q; } void display() { cout<<real<<”+j”<<imag<<endl; } friend Example operator-(Example X1,Example X2); }; Example operator-(Example X1, Example X2) { Example E; E.real= X1.real-X2.real; E.imag= X1.imag-X2.imag; return E; } int main() { Example obj1(10,20); Example obj2(5,5); Example obj3(0,0); cout<<“Subtraction is” obj3= obj1- obj2; obj3.display(); return 0; } |
//Defines operator function to overload -
//Invokes overloaded binary -
|
Overloading Relational and Logical Operators
Equality(==)
Less than(<)
Less than equal to(<=)
Greater than(>)
Greater than equal to(>=)
Inequality(!=)
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
a!=b return !(a==b)
a>b return(b<a)
a<=b return!(b<a)
a>=b return!(a<b)
bool class_name::operator symbol(const class_name & rhs)
{
Compare this and rhs and return true and false accordingly
}
Where rhs= right hand side operand
#include<iostream>
using namespace std;
class overload
{
private:
int a,b;
public:
overload (int x, int y) //constructor to initialize variables
{
a=x;
b=y;
}
bool operator <(const overload &o1) // overloading < operator
{
If( (a<o1.a)&&(b<o1.b))
{
return true;
else
return false;
}
bool operator ==(const overload &o1) // overloading == operator
{
return ((a==o1.a)&&(b==o1.b));
}
};
int main()
{
overload object1(10,20);
overload object2(11,21);
if(object1<object2) // Compare two objects
cout<<”Values of object 1 are less than values of Object2”;
else
cout<<”Values of object 1 are not less than values of Object2”;
if(object1==object2)
cout<<”Values of object 1 are equal to values of Object2”;
else
cout<<”Values of object 1 are not equal to values of Object2”;
return 0;
}
Overloading new delete and Assignment Operator
new and delete operators can be overloaded using following code.
void *operator new(size_t size)
{
return malloc(size); //Perform allocation
}
Where size is number of bytes of memory of data type size_t.
Return type of overloaded new must be void* as it must return pointer to memory that it allocates or throw bad_alloc exception if an allocation error occurs.
void *operator delete(void *P)
{
free(*P); // free memory pointed by P
}
Where *P is a pointer to memory to be freed.
Program
Program to overload new and delete operator.
#include<iostream>
using namespace std;
class Employee
{
int id;
int salary;
public:
Employee(int x, int y)
{
id=x;
salary=y;
}
void display()
{
cout<<”Employee id:”<<id<<endl;
cout<<”Employee salary:”<<salary<<endl;
}
void *operator new(size_t size );
void operator delete(void *p);
};
void *Employee::operator new(size_t size )
{
void *p;
cout<<”Overloading new”<<endl;
p=malloc(size);
if(!p)
{
bad_alloc b;
throw b;
}
return p;
}
void Employee:: operator delete(void *p)
{
cout<<”Overloading delete”<<endl;
free(p);
}
int main()
{
Employee *E1,*E2;
try
{
E1= new Employee(10,50000);
}catch(bad_alloc ba)
{
cout<<”Allocation error for E1”;
return 1;
}
try
{
E2= new Employee(11,60000);
}catch(bad_alloc ba)
{
cout<<”Allocation error for E2”;
return 1;
}
E1->display();
E2->display();
delete E1;
delete E2;
return 0;
}
Output
Overloading new
Overloading new
10 50000
11 60000
Overloading delete
Overloading delete
2. Overloading Assignment Operator
We can assign one object to another by overloading assignment operator.
Program
Write a C++ program to overload assignment operator(=) .
#include<iostream> using namespace std ; class Example { int a,b; public: Example(int p, int q) { a=p; b=q; }
void display() { cout<<a<<” ”<<b<<endl; } Example operator=(Example X); }; Example Example:: operator=(Example X) { a= X.a; b= X.b; return this*; } int main() { Example obj1(10,20); Example obj2(0,0); cout<<”Before Assignment”;
obj2.display(); obj2= obj1; cout<<”After Assignment”; obj2.display(); return 0; } |
//parameterized constructor
// Step 1 overloads =
// Step 2 Defines operator function to overload =
// Step 3 Invokes overloaded assignment operator |
Explanation
Example Example:: operator=(Example X)
{
a= X.a;
b= X.b;
return this*;
}
Output
Before Assignment
a 0 b 0
After Assignment
a 10 b 20
Rules of Operator Overloading
Operators which cannot be overloaded
All C++ operators can be overloaded except following
Operators which cannot be overloaded by using Friend Function
Following operators cannot be overloaded using friends
Rules for operator overloading
F1→ void accept(int x);
F2→ void accept(float y);
F3→ void accept(int x, int y);
Here accept function is overloaded.
int add(int x, int y);
float add(int x, int y);
Here add functions have different return types but they have same argument list. So they are not overloaded functions.
Thus return type does not play any role in function overloading.
Table : Function prototypes and required function calls
Sr. No. | Function Protoypes | Function calls |
1. | void accept(int x); | accept(10); |
2. | void accept(float y); | accept(1.5); |
3. | void accept(int x, int y); | accept(10,20); |
Program
Write a C++ program to calculate the area of circle, rectangle and triangle using function overloading.
Solution :
#include<iostream>
using namespace std ;
#include<conio.h>
#define pi 3.14
class Sample //Defines class Sample
{
public:
void area(int x) // 1.Calculates area of circle
{
int y= pi*x*x;
cout<<“Area of circle is ”<<y;
}
void area(int a, int b) // 2.Calculates area of rectangle
{
int c= a*b;
cout<<“Area of rectangle is”<<c;
}
void area(float p,float q) // 3.Calculates area of triangle
{
int s= 0.5*p*q;
cout<<“area of triangle is”<<s;
}
};
int main()
{
Sample obj ;
obj.area(10); // Step 4 Function call for area for circle
obj.area(10,20); // Function call for area for rectangle
obj.area(1.5,2.5); // Function call for area for triangle
return0 ;
}
Explanation
This program calculates area for circle, rectangle and triangle. For this we are overloading “area” function.
Step 1 : Here x denotes radius of circle. This version of “area” calculates area of circle and hence radius is passed as parameter.
void area(int x) { int y= pi*x*x; cout<<“Area of circle is”<<y; } |
//Calculates area of circle
|
Step 2 : Here a and b denote length and breadth of rectangle. This version of “area” calculates area of rectangle and hence length and breadth are passed as parameters.
void area(int a,int b) { int c= a*b; cout<<“Area of rectangle is”<<c; } |
//Calculates area of Rectangle |
Step 3 : Here p and q denote base and height of triangle. This version of “area” calculates area of triangle and hence base and height are passed as parameters.
void area(float p,float q) { int s= 0.5*p*q; cout<<“area of triangle is”<<s; } |
//Calculates area of triangle |
Step 4 : It denotes function calls for different versions of area depending upon type of geometrical figure.
int main() { Sample obj; obj.area(10); obj.area(10,20); obj.area(1.5,2.5); return0; } |
//Function call for area for circle //Function call for area for rectangle //Function call for area for triangle |
template <class Ttype> return-type function-name(parameter list)
{
//body of function
}
Or
template <class Ttype>
return-type function-name(parameter list)
{
//body of function
}
Where Ttype -> data type used by the function.
Program
Write a C++ program for a function template that returns the maximum of two values.
Solution :
#include<iostream.h> template <class T> void max1(T x,T y) { if(x>y) cout<<x<< “is greater”; else cout<<y<<”is greater”; } int main() { cout<<"\nInteger"<<max1(3,7); cout<<"\nFloat"<<max1(44.66,22.13); cout<<"\nCharacter "<<max1('t','p'); return 0; } |
// Step 1
//Here, condition is checked
//Step 2 Integers are passed. //Step 3 float are passed. // Step 4 Characters are passed. |
Explanation
Step 1 : Function template for finding maximum of two numbers is written where T represents generic data type. T will be replaced by specific data type depending upon type of parameter passed to function ‘max1’.
void max1 (Tx, Ty)
Step 2 : When we pass integer value to the function, ‘T’ will act as integer type. Thus it finds maximum of two integers.
cout<<"\nInteger"<<max1(3,7);
Step 3 : When we pass float value to the function, ‘T’ will act as float type. Thus it finds maximum of two floats.
cout<<"\nFloat "<<max1(44.66,22.13);
Step 4 : When we passed character value to the function, ‘T’ will act as character type. Thus it finds maximum of two characters.
cout<<"\nCharacter "<<max1('t','p');
Thus Single function is working for all three datatypes.
Output
Integer : 7
Float : 44.66
Character : t
Program
Write a C++ program to swap two numbers using concept of function template.
Solution :
#include<iostream> using namespace std; template <class T> void swapnums(T &x,T &y) { T temp; temp=x x=y; y=temp; } int main() { swapnums (10, 11); swapnums (10.5, 11.5); swapnums (‘A’, ‘D’); return 0; } |
//Function template for swapping
|
Program
Write a program in C++ for bubble sort using function template.
Solution :
#include<iostream> using namespace std; template <class T> void bubblesort(T A[], int n) { for(int i=0;i<=n-1;i++) for(int j=n-1;i<j;j--) if(A[j]<A[j-1]) { swap (A[j], A[j-1]) } template <class X> void swap(X &p, X &q) { X temp=p; p=q; q=temp; }
int main() { int array[5]; cout<<“Enter elements of array”; for(int i=0;i<5;i++) { cin>>a[i]; } bubblesort(array,5); cout<<“Sorted array”; for(int i=0;i<5;i++) { cout<<array[i]<<“”; return 0; } |
//template function for bubble sort
// calls template function for swap
// template function for swap
//accept array elements for sorting
//calls template function for sorting |
Output
Enter elements of array
25 15 30 10 50
Sorted array 10 15 25 30 50
Program
Write a program to display integer value, float value, character and string by using single function.
Solution :
#include<iostream>
using namespace std;
#include<conio.h>
template <class T>
void display(T x)
{
cout<<x<<"\n";
}
int main()
{
display(20);
display(44.3);
display('A');
display("welcome");
return0;
}
Output
20
44.3
A
Template Arguments in Member Function Template
template<class T1, class T2,.... class Tn>
return-type function-name(T1 arg, T2 arg,...Tn arg)
{
Function Body
}
Example :
template<class T1, class T2>
void Demo(T1 a, T2 b)
{
cout<<a< “ ”<<b;
}
Program
Program to illustrate multiple template arguments in member function.
Solution :
#include<iostream>
using namespace std;
#include<conio.h>
template<class T1, class T2>// Step 1
void Demo(T1 a, T2 b)
{
cout<<a<<” ”<<b;
}
void main()
{
Demo(10,20.5); // Step 2
Demo(20.9, ‘A’);// Step 3
Demo(‘X’, “Object Oriented”);// Step 4
}
Explanation
Step 1 : This program designs template function with two arguments of generic type T1 and T2.
Step 2 : The statement
Demo(10,20.5)
invokes template function. T1 will be replaced by 10(int) and T2 will be replaced by 20.5(float).
Step 3 : The statement
Demo(20.9, ‘A’)
invokes template function. T1 will be replaced by 20.9 (float) and T2 will be replaced by A(char).
Step 4 :
Demo(‘X’, “Object Oriented”)
invokes template function. T1 will be replaced by X(char) and T2 will be replaced by Object Oriented (string).
#include<iostream> |
|
| //Template function |
template <class T> |
|
void display(T x) |
|
{ |
|
cout<<"\n Inside template function : x : "<<x; | //Take any type of data (like int, float, string etc.) |
} |
|
//Normal function |
|
void display(int x) |
|
{ |
|
cout<<"\n Inside normal function : x : "<<x; | //Take only integer type. |
} | //This function overrides template function |
void main () |
|
{ |
|
display(21.45); | //calls template function |
display(45); | //calls normal function |
display("Object oriented"); | // calls template function |
} |
|
Output
Inside template function : x :21.45
Inside normal function : x : 45
Inside template function : x : Object Oriented
Function Overloading Vs Function Template
Function overloading | Function Template |
Data types used in overloaded function are primitive data types Eg. void add(int a, int b); void add(float a, int b);
Primitive data type | Data types used in template function are generic data types template<class T1, class T2> void Demo(T1 a, T2 b) Generic type |
All the versions of overloaded functions must be explicitly specified. Eg. P1. void add(int a, int b); P2. void add(float a, int b); P3. void add(int a, int b, int c); Function call add(10,20) will invoke P1 While add(10.5, 5) will invoke P2 | Function template takes various versions depending on the type of argument passed to it. template<class T1, class T2> void Demo(T1 a, T2 b) Demo function will take version Demo(int, int) for function call Demo(10,20). Similarly for function call Demo(10.5,5) version will be Demo(float, int) . Thus function template automatically overloads itself. |
It does not support generic programming. | It supports generic programming. |
Every overloaded function will have separate definition. | Function template have same definition for all versions of it. |
Example: void Data(int a, int b, int c); void Data(float a, float b, float c); void Data(int a, float b);
| Example: template<class T1, class T2> void Demo(T1 a, T2 b) { } |
Syntax
template<class T>
class class_name
{
-------------
class members
-------------
};
Program
Consider class Demo, where we want to find average of three numbers(numbers can be integer or float).
Solution :
#include<iostream>
using namespace std;
template <class T>
class Demo //Step 1
{
private:
T n1,n2,n3;
public:
Demo(T x, T y, T z)
{
n1=x;
n2=y;
n3=z;
}
void avg() //Step 2
{
cout<<" "<<(n1+n2+n3)/3;
}
};
int main()
{
Demo<int>s1(10,20,30); //Step 3
Demo<float>s2(50.5,40.5,30.5); //Step 4
cout<<"\n Average = "; //Step 5
s1.avg();
cout<<"\n Average = ";
s2.avg();
return 0;
}
Explanation
Steps
Step 1 : ‘Demo’ is a template class that defines function ‘avg’.
Class Demo
Step 2 : ‘avg’ function calculates average of three numbers.
void avg()
{
cout<<" "<<(n1+n2+n3)/3;
}
Step 3 : It creates object s1 that stores integer type variables.
Demo<int>s1(10,20,30);
Step 4 : It creates object s2 that stores float type variables.
Demo<float>s2(50.5,40.5,30.5);
Step 5 : Calculates average of three integer numbers.
cout<<"\n Average = ";
s1.avg();
Step 6 : Calculates average of three float numbers.
cout<<"\n Average = ";
s2.avg();
Output
Average = 20
Average = 40.5
Single Inheritance
● It consists of single base and single derived class.
● Derived class inherits all the protected and public members from single base class.
● Private data members of base class will not be inherited.
☞ General form
class derived-class : access specifier base-class
{
//Body of derived class
};
Fig: Single Inheritance
| class A { //Body of class A }; class B : public A { //Body of class B }; |
Program
Write a program in C++ to illustrate single inheritance.
Solution :
#include<iostream> using namespace std ; class Employee { protected: int id; char name[10]; public: void accept() { cout<<“Enter id of employee”; cin>>id; cout<<“Enter name of employee”; cin>>name; } }; class Salary: public Employee { protected: float amount, hra, da, basic; public: void getdata() { accept(); cout<<“enter basic, da and hra”; cin>>basic>>da>>hra; } void display() { amount=basic+da+hra; cout<<“NAME:”<<name<<endl; cout<<“ID:”<<id<<endl; cout<<“SALARY:”<<amount; } }; int main() { Salary S; S.getdata(); S.display(); return 0 ; } | //Declares header file
//Step 1 Declares and defines base class Employee
//Step 2 Declares id and name under protected section
//Step 3 Defines accept function under public section
//Accepting id and name of employee
//End of accept function //End of class Employee //Step 4 Create derived class Salary from base class Employee
//Step 5 Declares data members under protected section
//Step 6 Defines getdata function
//Step 7 Calls accept function //Accepting details of salary
//End of getdata function //Step 8 Defines display function
//Calculates salary
//Displaying name id and salary of employee
//End of display function //End of derived class salary //Starts main function
//Step 9 Creates object S //Step 10 Calls getdata function //Calls display function |
Explanation
Step 1 : Creates base class Employee.
As it is single inheritance only one base class is there.
class Employee //Declares and defines base class Employee
Step 2 : id and name are declared under protected section so that they are accessible to its immediate derived class .
protected:
int id; //Declares id and name under protected section
char name[10];
Step 3 : Accept function accepts details of employee.
void accept() //Defines accept function under public section
{
cout<<“Enter id of employee”;
//Accepting id and name of employee
cin>>id;
cout<<“Enter name of employee”;
cin>>name;
} //End of accept function
Step 4 : Creates derived class Salary from base class under public derivation.
All protected members remains protected and public members remain public in public derivation.
class Salary: public Employee
//Create derived class Salary from base class Employee
So data members in class Salary are as follows :
Salary | |
Protected | Public |
id name amount hra da basic |
accept() getdata() display() |
Step 5 : Declares basic, hra, da for calculation of salary.
float amount, hra, da, basic;
Step 6 : getdata accepts hra, da and basic to calculate salary.
void getdata() //Defines getdata function
Step 7 : getdata() calls accept() to get id and name.
Member function can call another member function of same class or base class directly.
getdata() calls accept() directly as it belongs to base class.
accept(); //Calls accept function
cout<<“enter basic, da and hra”;
cin>>basic>>da>>hra; //Accepting details of salary
Step 8 : Calculates salary and displays details of employee
void display() //Defines display function
{
amount=basic+da+hra; //Calculates salary
cout<<“NAME:”<<name<<endl;
//Displaying name id and salary of employee
cout<<“ID:”<<id<<endl;
cout<<“SALARY:”<<amount;
} //End of display function
Step 9 : Creates object of derived class Salary.
In inheritance object of derived class is created because derived class has access to base class but base class does not have any knowledge of its derived classes down the hierarchy.
Salary S; //Creates object S
Step 10 : Calls member functions with the help of objects and dot operator.
S.getdata(); //Calls getdata function
S.display(); //Calls display function
☞ Multiple inheritance with syntax
● It consists of multiple base classes and single derived class.
● Derived class inherits protected and public members from multiple base classes.
● If there are two base classes, then derived class inherits features from both the classes.
☞ General form
class derived-class : access specifier base-class1, access specifier base-class2
{
//Body of derived class
};
Fig: Multiple Inheritance
| class A { //Body of class A }; class B { //Body of class B }; class C : public A, public B { //Body of class C }; |
⮚ Program
Write a C++ program to illustrate multiple inheritance.
Fig. P. 5.4.2
Solution :
Fig. P. 5.4.2shows multiple inheritance where Employee, Person, Manager are classes and name, age, Department, salary, are data members of these classes.
#include<iostream> using namespace std ; class Person { protected: char Name[10]; int age; public: void accept() { cout<<“Enter name of person”; cin>>Name; cout<<“Enter age of person”; cin>> age; } }; class Employee { protected: char dept[20]; public: void getdata() { cout<<“Enter department of employee”; cin>> dept; } }; class Manager : public Person ,public Employee { protected: int salary; public: void acceptdata() { cout<<“Enter salary of employee”; cin>>salary; } void display() { cout<<“Name of Manager is”<<name; cout<<“Age of Manager is”<<age; cout<<“Department of Manager is”<<dept; cout<<“Salary of Manager is”<<salary; } }; int main() { Manager obj; obj.accept(); obj.getdata(); obj.acceptdata(); obj.display(); return 0; } |
//Step 1 Defines base class Person
//Accept details of Person
//Step 2 Defines another base class Employee
//Accept details of Employee
//Step 3 Defines sub class Manager
//Accept details of salary
//Displays details of Manager
//Defines main function
//Creates object of Manager //Access member functions of classes to display details of Manager. |
Explanation
Step 1 : Defines base class Person with data members name and age and function accept().
Data members are declared under protected section so that they are accessible to derived class.
class Person { protected: char Name[10]; int age; public: void accept() { cout<<“Enter name of person”; cin>>Name; cout<<“Enter age of person”; cin>> age; } }; | //Defines base class Person
//Accept details of Person
|
Step 2 : Defines another base class Employee.
class Employee { protected: char dept[20]; public: void getdata() { cout<<“Enter department of employee”; cin>> dept; }}; | //Defines another base class Employee
//Accept details of Employee
|
Step 3 : Defines sub class Manager that is derived from two classes Person and Employee.
● Data member is salary.
● acceptdata() function accepts salary of employee.
● display() function displays all the details of Manager.
● display() function of subclass Manager can access all the data members of super classes as they are declared under protected section and inherited under public derivation.
class Manager : public Person ,public Employee { protected: int salary; public: void acceptdata() { cout<<“Enter salary of employee”; cin>>salary; } void display() { cout<<“Name of Manager is”<<name; cout<<“Age of Manager is”<<age; cout<<“Department of Manager is”<<dept; cout<<“Salary of Manager is”<<salary; } }; | //Defines sub class Manager
//Accept details of salary
//Displays details of Manager
|
Step 4 : Creates object of derived class .This object can access all the public and protected data members and member functions of super classes.
Manager obj; | //Creates object of Manager |
Step 5 : Calls accept() function.
obj.accept(); |
Step 6 : Calls getdata() function.
obj.getdata(); |
Step 7 : Calls acceptdata() function.
obj.acceptdata(); |
Step 8 : Calls display()function.
obj.display(); |
class Employee
{
};
class Project: public virtual Employee
{
};
class Salary: virtual public Employee
{
};
class Employee_Info: public Project, public Salary
{
};
Program is as follows :
class Employee { protected: char Emp_Name[10]; char dept[20]; public: void accept() { cout<<”Enter name of employee”; cin>>Emp_Name; cout<<”Enter department of employee”; cin>> dept; } }; class Project : public virtual Employee { protected: char Pro_name[10]; int Pro_id; public: void getdata() { cout<<”Enter name of project”; cin>>Pro_name; cout<<”Enter id of project”; cin>>Pro_id; } }; class Salary : virtual public Employee { protected: int amount; public: void acceptdata() { cout<<”Enter amount of salary”; cin>>amount; } }; class Emp_Info : public Project, public Salary { public: void display() { cout<<”Employee details are” cout<<”Name of employee is”<<Emp_Name; cout<<”Department of employee is”<<dept; cout<<”Name of Project is”<<Pro_name; cout<<” Id of Project is”<<Pro_id; cout<<”Salary of employee is”<<amount; } }; int main() { Emp_Info obj; obj.accept(); obj.getdata(); obj.acceptdata(); obj.display(); return 0; } | //Defines base class Employee
//Accept details of employee
//Defines sub class project that inherits Employee virtually
//Accept details of Project
//Accept details of salary
//Defines sub class Emp_Info
//Displays details of employee
//Defines main function
//Creates object of Emp_Info //Access member functions of classes to display details of employee. |
Output
Enter name of employee
John Mathew
Enter department of employee
Information Technology
Enter name of project
Employee Database
Enter id of project
11
Enter amount of salary
50000
Employee details are
Name of employee is: John Mathew
Department of employee is: Information Technology
Name of Project is: Employee Database
Id of Project is : 11
Salary of employee is: 50000
Virtual and public keywords can be used in either order.
Abstract class is a base class , all the concrete classes can inherit abstract class.
Characteristic of Abstract class.
Example
Example
Output is – Child id is 10.
Parent id is 80.