Unit Iv CPP
Unit Iv CPP
Creating two or more members having the same name but different in
number or type of parameter/arguments is known as overloading.
Types of overloading
Function Overloading
#include<iostream>
using namespace std;
class Calculate
{
public:
int add(int a,int b)
{
return a + b;
}
Output
class className
{ ... .. ...
public returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex()
{
real =0;
imag = 0;
}
void input() {
cout << "Enter Real part : ";
cin >> real;
cout << "\nEnter Imaginary part : ";
cin >> imag; }
Complex operator + (Complex c2) // Operator overloading
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number : "<< real << imag << "i";
else
cout << "Output Complex number : " << real << " + " << imag <<"i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number : \n";
c1.input();
cout << endl;
cout<<"Enter second complex number : \n";
c2.input();
/* In case of operator overloading of binary
operators in C++ programming, the object on right hand
side of operator is always assumed as argument by
compiler.*/
result = c1 + c2;
result.output();
return 0;
}
Output
A friend function can access the private and protected data of a class. We
declare a friend function using the friend keyword inside the body of the
class.
Syntax
class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Characteristics of a Friend function:
1. The function is not in the scope of the class to which it has been
declared as a friend.
Characteristics of a Friend function: contd…
2. It cannot be called using the object as it is not in the scope of that
class.
3. It can be invoked like a normal function without using the object.
4. It cannot access the member names directly and has to use an object
name and dot membership operator with the member name.
5. It can be declared either in the private or the public part.
Program Example
#include<iostream>
using namespace std;
class integer
{
int num1, num2;
public:
void setValue()
{
num1 = 50;
num2 = 30;
}
friend int mean(integer s); //Declaration of friend Function
};
int mean(integer s) //friend function definition
{
return int(s.num1+s.num2) / 2.0;
}
int main()
{
integer c;
c.setValue();
cout<< "Mean value:" <<mean(c);
return 0;
}
Output
Mean value:40
Important points about operator overloading using friend function
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single Inheritance is defined as the inheritance in which a derived class
is inherited from the only one base class.
In the diagram under Single inheritance box labelled “Base Class” is the
base class or Parent Class, and box labelled “Derived Class” is the Child
Class derived class.
The child class can inherit all the members of the base class according to
the visibility mode (i.e., private, protected, and public) that is specified
during the inheritance.
Syntax
class BaseClass
{
----
---- // code of class BaseClass
}
The colon indicates that the derived-class-name is derived from the base-
class name.
The Visibility mode is optional and, if present, may be either private or
public.
The default Visibility-mode is private. Visibility mode specifies whether the
features of the base class Are- privately derived or publicly derived.
Examples:
In both the cases, the private members are not inherited and therefore ,
the private members of a base class will never become the members of
its derived class.
A base class B and a derived class D. The class B contains one private
data member, one public data member, and three public member
functions. The class D contains one private data member and two public
member functions.
SINGLE INHERITANCE : PUBLIC
#include <iostream.h>
using namespace std;
class B
{
int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(voi d)
};
class D : public B // public derivation
{
int c;
public:
void mul (void);
void display (void);
};
Void B :: get_ab (void);
{ a=5;b=10;}
int B:: get_a()
{
return a;
}
void B show_a{)
{
cout « a ;
}
void D :: mul()
{
c=b*get_a();
}
void D :: display()
{
cout « “a = " <<qet_a();
cout « 'b = " <<b;
cout «”c = " <<c;
}
Int main()
{
D d;
d.get_ab();
d.mul ();
d.show_a();
d.display();
}
Output
a=5
a =5
b =10
c = 50
a=5
b= 20
c = 100
SINGLE INHERITANCE : PRIVATE
#include <iostream.h>
using namespace std;
class B
{
Int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(voi d)
};
class D : private B //private derivation
{
int c;
public:
void mul (void);
void display (void);
};
void B :: get_ab(void);
{
Cout<<”enter a and b”;
Cin>>a>>b
}
int B:: get_a()
{ return a; }
void B :: show_a{)
{
cout « a ;
}
void D :: mul()
{
get_ab();
c=b*get_a();// a can’t be used directly
}
void D :: display()
{
Show_a()
cout « 'b = " <<b;
cout «”c = " <<c;
}
int main()
{
D d;
d.mul (); //d.get_ab(); won’t work Result
OUTPUT
d.display(); //d.show_a();won’t work A=5
//d.b=20; b has the private data. won’t work B=10
d.mul (); C=50
d.display();
}
Making a Private Member Inheritable
The class A serves as a base class for the derived class B„ which in turn
serves as a base class for the derived class C. The class B is known as
intermediate base class since it provides a link for the inheritance
between A and C. The chain ABC is known as inheritance path.
Example
Assume that the test results of a batch of students are stored in three
different classes . Class student stores the roll-number, class test store the
marks obtained in two subjects and class result contains the total marks,
obtained in the test. The class result can inherit the details of the marks
obtained in the test and the roll-number of students through multilevel
inheritance
class student
{
Protected:
int roll_number;
public:
void get_number(int );
void put_number (void) ;
};
Include <iostream.h>
class student
{
Protected:
int roll_number;
public:
void get_number(int );
void put_number (void) ;
};
void student ::get_number(int a)
{
Roll_ number=a;
}
void student:: put_number()
{
cout « "Roll Number: “ « roll_number « "\n";
}
class test : public student // First level derivation
{
protected:
float subl;
float sub2;
public:
void get_marks (float , float);
void put_mark(void);
}
void test ::get_marks(float x, float y)
{ Sub1 = x; Sub2 = y; }
void test:: put _marks()
{
cout « "marks in SUB1 =" subl « "\n";
cout « "marks fn SUB2= " « sub2 « "\n";
}
class result : public test // Second level derivation
{
float total; // private by default
public:
void display(void);
};
void result :: display(void)
{
Total= sub1+sub2;
Put_number();
Put_mark();
Cout<<”total=”<<total;
}
main() {
Result student1
Student1.get_number(1000);
Student1.get_markr(85,95);
Student1.display();
}
Multiple inheritance
Where visibility may be either public or private. The base class are
separated by commas.
Example;
class P : public M , public N
{
public:
void display(void);
}
Program
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;;
public:
void get_n(int);
};
Class p : public M , Public N
{
Public :
Void display(void);
};
void M : : get_m(int x)
{
m=x;
}
void N :: get_n(int y)
{
n= y:
}
void P :: display(void)
{
cout « “m=”<<m;
cout<< "n =”« n ;
cout<<”m*n=” <<m*n;
}
main()
{
P p;
p.get_m(10);
p.get_n(20);
p.display();
}
Output
m=10
n=20
m*n=200
Hybrid Inheritance
Student
Sports
Test
Result
include <iostream.h>
class student
{
protected:
int roll_number;
public:
void get_number (int a)
{
Roll_ number= a;
}
void put_number (void)
{
cout "Roll No=”" « roll_number;
}
};
class test : public student
{
protected:
float part1, part2;
public:
void get_ marks(float x, float y)
{ Part1=x; part2 = y; }
yoid put_Marks(void)
{
cout « marks obtained: " « "\n"
cout<<"Part1 =" « part1;
cout« "Part2= " « part2 "\n”;
} };
class sports
{
protected:
float score;
public:;
void get_ score(float s)
{
Score=s;
}
void put_score(void)
{
cout « 'Sports wt:= " « score ;
} };
class result :: public test, public sports
{
float total ;
public;
void display (void)
};
void result :: display(void)
{
total = part1+ part2 + score;
put_number();
put_marks();
put_score();
cout « "Total Score: " « total;
}
main()
{
result student1;
student_1.get_number(1234);
student_1.get_marks(78,88);
student_1.get_score(6);
student_1.display();
}
Hierarchical Inheritance
int main()
{
B b1; //b1 is object of Derived class 1
b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
}
Enter Number : 2
Square of the number : 4
Enter Number : 3
Cube of the number :: 27
Virtual Base Classes
Virtual Base Classes require the use of both the multiple and multilevel
inheritance. Consider a situation where all the three kinds of inheritance,
namely, multilevel, multiple and hierarchical inheritance, are involved, The
'child' has. two direct base classes 'parent1' and 'parents2’ which
themselves have a common base class 'grandparent'. The 'child' inherits the
traits of 'grandparent' via two separate paths. It can also inherit directly as
shown by the broken line. The 'grandparent‘ is sometimes referred to as
indirect have class.
All the public and protected members of grandparent are inherited into
'child' twice, first via parentl1 and again via 'parent2', This means, 'child'
would have duplicate sets of the members inherited from 'grandparent'.
The duplication of inherited members due to these multiple paths can be
avoided by using the common base class (ancestor class) as virtual base
class.
class A
{
….
….
}
Class Bl : virtual public A // parent1
{
….
….
}
class B2 : public virtual A // parent2
{
….
….
};
class C : public B1, public B2 // child
{
….
…. // only one copy of A will be inherited
}
Students contains roll number. This roll number will be inherited test class.
So test class contains roll number. Students contains roll number. this roll
number will be inherited sports class. So sports class contains roll number.
Now test class and sports class will be inherited the result class . so the
result class contains roll number twice.
PROGRAM -VIRTUAL BASE CLASS
include <1ostream.h>
Class student
{
Protected:
Int roll_number;
Public:
void get_number(int a)
{
Roll_ number = a;
}
void put_number (void)
{
Cout<< "roll No=”,<< roll_number « '\n";
};
class test : virtual public student
{
protected:
float partl, part2;
public:
void get_marks( float x, float y)
{
part1= x ;
part2= y;
}
void put_marks(void)
{
cout « "Marks obtained=”;
cout<<part1;
cout<<part2;
}
class sports : public virtual student
{
protected;
float score;
public:
void get_ score(float s)
{
score =s;
}
void put_score(void)
{
cout "Sports wt=”<< score;
};
class result : public test, public sports
{
Float total;
public:
void display (void);
}
void result :: display(void)
{
total = part1+ part2 + score;
put_number ( );
Put_marks();
put_score();
cout<<” Total Score: "<< total;
}
main()
{
result student_l;
stuctent_l .get_number(678) -„
student_1.get_marks(50.9,67.8);
student_l . get_score(7.0);
student_l.display();
return 0;
}
An abstract class is a class that is designed to be specifically used as a
base class. An abstract class contains at least one pure virtual function.
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:
#include <iostream>
using namespace std;
class Shape // Abstract class
{
protected:
float dimension;
public:
void getDimension()
{
cin >> dimension;
}
virtual float calculateArea() = 0; // pure virtual Function
};
class Square : public Shape // Derived class
{
public:
float calculateArea()
{
return dimension * dimension;
}
};
Derived Class
#include <iostream>
using namespace std;
class Parent // Base Class
{
public:
Parent() // Base Class Constructor
{
cout << "Inside Base Class" << endl;
}
};
class Child : public Parent // Child Class
{
public:
Child() // Clild Class Constructor
{
cout << "Inside Child Class" << endl;
}
};
Output:
Inside Base Class
Inside Child Class
Member Class Class
A class in C++ is a user-defined type or data structure declared with
keyword class that has data and functions (also called member
variables and member functions) as its members whose access is
governed by the three access specifiers private, protected or public.
By default access to members of a C++ class is private Nested ClassA
declaration of a class may appear within another class. Such
declaration declares a nested class.
Explanation
class EnclosingClass
{
class NestedClass
{
---
---
};
};
Pointer to Objects
void MyClass::showNumber()
{
cout << "The Number is "<<num << "\n";
}
int main()
{
MyClass object, *p; // an object is declared and a pointer to it
object.setNumber(100); // object is accessed directly
object.showNumber();
p = &object; // the address of the object is assigned to p
p->showNumber(); // object is accessed using the pointer
return 0;
}
Output
The Number is 100
The Number is 100
Pointer to Objects Program 2
#include<iostream>
using namespace std;
class Complex
{
int real, imaginary;
public:
void put_Data()
{
cout << "The real part is “ << real << endl;
cout << "The imaginary part is “ << imaginary << endl;
}
void set_Data(int x, int y)
{
real = x;
imaginary = y;
}
};
int main()
{
Complex *ptr = new Complex;
ptr->set_Data(1, 54);
ptr->put_Data();
Complex *ptr1 = new Complex[4]; // Array of Objects
ptr1->set_Data(1, 4);
ptr1->put_Data();
return 0;
}
Output
The real part is 1
The imaginary part is 54
The real part is 1
The imaginary part is 4
this Pointer
Output
101 Sonoo 890000
102 Nakul 59000
Pointer to Derived Class
2. To access the variable of the base class, a base class pointer will be
used. So, a pointer is a type of base class, and it can access all,
public function and variables of the base class since the pointer is
of the base class, this is known as a binding pointer.
Class B
{
---
---
};
Class D : Public B
{
----
----
};
B *cptr; // here is pointer to class B type variable
B b; // base object
D d; // derived object
cptr=&b; // cptr points to object b
we can make in the above example cptr to point to the object d as
follows
cptr=&d; // cptr points to object d
This is perfectly valid with C++ language because d is an object derived
from the class B
However these is a problem in using cptr to access the public of the
derived class D. using cptr we can access only those members which are
inherited from B and not the member that originally belongs to D. in case a
member of D class has the same name as one of the members of class B,
then any reference to that member by cptr variable will always access the
base class member.
Pointer to Derived Class Program
#include<iostream>
using namespace std;
class BC
{
public:
int b;
void show()
{
cout << "b = : " << b << "\n";
}
};
class DC: public BC
{
public:
int d;
void show()
{
cout << "b = : " << b << "\n";
cout << "d = : " << d << "\n";
}
};
Pointer to Derived Class Program
int main()
{
BC *bptr; // base pointer
BC base;
bptr = &base; //base address
bptr->b = 100; // access BC via base pointer
cout << "bptr points to base object \n";
bptr->show();
Output
Printed from derived Class print() Function
Pure virtual Functions are virtual functions with no definition. They start
with virtual keyword and ends with = 0. Here is the syntax for a pure
virtual function,
Syntax 1
virtual void functionname() = 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.
Syntax 2
virtual void functionname() {}
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
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;
};
Example Program
#include <iostream>
using namespace std;
class Shape // Abstract class
{
protected:
float dimension;
public:
void getDimension()
{
cin >> dimension;
}
virtual float calculateArea() = 0; // Pure Virtual Function
};
class Square : public Shape // Derived class
{
public:
float calculateArea()
{
return dimension * dimension;
}
};
1. Compile-time Polymorphism.
2. Runtime Polymorphism.
Function overloading - Compile Time Polymorphism
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is known
as Function Overloading. Functions can be overloaded by changing the
number of arguments or/and changing the type of arguments.
#include <iostream>
using namespace std;
int sum(int num1, int num2) // Function with 2 int parameters
{
return num1 + num2;
}
double sum(double num1, double num2) // unction with 2 double parameters
{
return num1 + num2;
}
int sum(int num1, int num2, int num3) // Function with 3 int parameters
{
return num1 + num2 + num3;
}
int main()
{
// Call function with 2 int parameters
cout << "Sum of Two Integers using sum() = " << sum(5, 6) << endl;
// Call function with 2 double parameters
cout << "Sum of Two Double using sum() = " << sum(5.5, 6.6) << endl;
// Call function with 3 int parameters
cout << "Sum of Three Integers using sum() = " << sum(5, 6, 7) <<
endl;
return 0;
}
Output
Sum of Two Integers using sum() = 11
Sum of Two Double using sum() = 12.1
Sum of Three Integers using sum() = 18
Operator overloading - Compile Time Polymorphism
Output
Incremented value of member "number" of object Count
using overloaded operator ++ is : 6
Virtual Functions - Runtime Polymorphism
Output
Rectangle class area : 70
Triangle class area : 25
THANK YOU