5. ďś Functions overloading
ď§ same function name but different parameters.
ď§ same function name with different signature
ď§ example of polymorphism(compile time)
ď§ overloaded functions should be there in same class.
8. Operator overloading
Operator overloading is a compile-time polymorphism in which the
operator is overloaded to provide the special meaning to the user-
defined data type.
⢠You can redefine built in operators except few:
⢠Scope resolution operator (::)
⢠sizeof
⢠member selector(.)
⢠member pointer selector(.*)
⢠ternary operator(?:)
10. Consider this example
class A
{
};
int main()
{
A a1,a2,a3;
a3= a1 + a2;
return 0;
}
This is not allowed, because the
addition operator â+â is
predefined to operate only on
built-in data types. But here,
âclass Aâ is a user-defined type,
so the compiler generates an
error. This is where the concept
of âOperator overloadingâ
comes in.
12. Operator overloading for Unary operators:
The unary operators operate on a single operand :
⢠The increment (++) and decrement (--) operators.
⢠The unary minus (-) operator.
⢠The logical not (!) operator.
13. Operator overloading for binary operators:
The binary operators operate on two operands :
+,
-,
*,
/,
%
a+b
14. Rules for Operator Overloading
ďąExisting operators can only be overloaded.
ďąThe overloaded operator contains at least one operand of
the user-defined data type.
ďąWhen unary operators are overloaded through a member
function take no explicit arguments, but, if they are
overloaded by a friend function, takes one argument.
ďąWhen binary operators are overloaded through a member
function takes one explicit argument, and if they are
overloaded through a friend function takes two explicit
arguments.
15. Overloading Unary Operator (using member function):
Example 1: Overload minus (-) unary operator.
⢠In unary operator function, no arguments should be passed.
⢠It works only with one class objects.
⢠It is an overloading of an operator operating on a single operand.
Class:
Assume that class Distance takes two data-members i.e. feet and inches.
Overload operator â
Create an operator function for unary minus operator (having single operand of
Distance Type)
Operator function (-) will change the sign of distance Object.
16. Overloading Unary Operator:
Output:
class Distance {
public:
// Data Members
int feet, inch;
// Constructor to initialize the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to perform decrement
void operator-()
{
this->feet = -f;
this->inch = -i;
cout << "nFeet & Inches(Decrement):n"
cout << feet << "'" << inch;
}
};
// Main Code
int main()
{
// Declare and Initialize
// the constructor
Distance d1(8, -9);
// Use (-) unary operator by
// Single operand
-d1;
return 0;
}
Feet & Inches(Decrement):
-8'9
17. Overloading Unary Operator (using member function):
Example 2: Overload unary ++ Operator
(both prefix and postfix fashion)
18. Binary Operator Overloading (using member function):
⢠In binary operator overloading function, there should be one argument to be passed.
⢠It is overloading of an operator operating on two operands.
Example: Example of class Distance, add two distance objects using binary +
operator
class Distance {
public:
// Data Members
int feet, inch;
// No Parameter/Default Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}
// Parameterized Constructor
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading (+) operator to perform addition
// of two Distance objects
Distance operator+(Distance &d2)
{
// Create an object to return
Distance d3;
// Perform addition of feet and inches
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;
// Return the resulting object
return d3;
}
};
19. Binary Operator Overloading (using member function):
Example Continue...
Output:
// Main Function Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);
// Declaring and Initializing second object
Distance d2(10, 2);
// Declaring third object
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
// Display the result
cout << "nTotal Feet & Inches:n"
cout << d3.feet << "'" << d3.inch;
return 0;
}
Total Feet & Inches:
18'11
20. Binary Operator Overloading (using member function):
Example Continue... (Pictorial View of working of Binary Operator: )
21. Overloading Binary Assignment (=) Operator
⢠Overload the assignment operator (=) just as you can other operators and it can be used to create
an object just like the copy constructor.
class Distance {
private:
int feet, inches;
public:
// required constructors
Distance() {
this->feet = 0;
this->inches = 0;
}
Distance(int f, int i) {
this->feet = f;
this->inches = i;
}
void operator = (const Distance &D2
) {
this->feet = D2.feet;
this->inches = D2.inches;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
cout << "First Distance : ";
D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();
// use assignment operator
D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
}
22. Overloading Binary Operator (Using Friend Function)
⢠In this approach, the operator overloading function must precede
with friend keyword, and declare a function class scope.
⢠Keeping in mind, friend operator function takes two parameters
in a binary operator, varies one parameter in a unary operator.
⢠All the working and implementation would same as binary
operator function except this function will be implemented
outside of the class scope.
23. Overloading Binary Operator (Using Friend Function)
Example: Example using the friend function to overload binary + operator.
class Distance {
public:
// Data Members
int feet, inch;
// No Parameter Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}
// Constructor to initialize the object's value
// Parameterized Constructor
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Declaring friend function using friend keyword
friend Distance operator+(Distance&, Distance&);
};
// Implementing friend function with two
parameters
Distance operator+(Distance& d1, Distance& d2)
// Call by reference
{
// Create an object to return
Distance d3;
// Perform addition of feet and inches
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;
// Return the resulting object
return d3;
}
24. Overloading Binary Operator (Using Friend Function)
Example Continue...
Output:
// Main Program Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);
// Declaring and Initializing second object
Distance d2(10, 2);
// Declaring third object
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
// Display the result
cout << "nTotal Feet & Inches:n "
cout << d3.feet << "'" << d3.inch;
return 0;
}
Total Feet & Inches:
18'11
25. Operators that cannot be overloaded using Friend Function
Following are the operators for which overloading is not possible in C++
using friend function:
1. function call operator ()
2. assignment operator =
3. class member access operator ->
4. subscripting operator [ ]
If these operators are overloaded using friend function, then program
will result with compilation error. These operators can be overloaded if
they are part of member functions.
NOTE: A friend function is a non-member function of the class to which it has been defined as
friend. Therefore, it just uses the functionality (functions and data) of the class. So, it does not
consist the implementation for that class. That's why it cannot be used to overload certain
class specific operators as listed above.
27. Virtual Base Class
⢠Virtual base classes are used in virtual inheritance
in a way of preventing multiple âinstancesâ of a
given class appearing in an inheritance hierarchy
when using multiple inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A.
This class is A is inherited by two other
classes B and C. Both these class are inherited into
another in a new class D as shown in figure below.
29. Virtual Base Class
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.
⢠Virtual base classes offer a way to save space and
avoid ambiguities in class hierarchies that use multiple
inheritances.
⢠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.
30. Virtual Base Class : An Example
Without
Virtual,
ambiguity
leads to a
Compiler Error
With Virtual
Base Class A,
No ambiguity,
Program runs
fine!
32. Function Overriding â Run-time Polymorphism
⢠It is the redefinition of base class function in its derived class with same
signature i.e., return type and parameters are exactly the same in both base
and derived classes.
⢠Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the
function of the derived class is executed.
This is known as function overriding in C++. The function in derived class
overrides the function in base class.
34. Function Overriding : Call Overridden Function Using Pointer
#include <iostream>
using namespace std;
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* ptr = &derived1;
// call function of Base class using ptr
ptr->print();
return 0;
}
35. Function Overriding : Call Overridden Function Using Pointer
⢠In last program, we have created a pointer of Base type named ptr. This pointer points
to the Derived object derived1
⢠When we call the print() function using ptr, it calls the overridden function from Base.
⢠This is because even though ptr points to a Derived object, it is actually of Base type.
So, it calls the member function of Base.
⢠In order to override the Base function instead of accessing it, we need to use virtual
functions in the Base class.
36. Problems in method overriding : Need of Virtual Function
⢠Overriding using base class pointer compiler donât know about pointer which
address is pointing because address will be decided at run time when memory
will be allocated.
⢠To over come this problem, we use virtual function.
⢠With the help of virtual function, we can override function at run time
37. Virtual Function in C++
⢠A virtual function is a member function which is declared within a base class and is
re-defined (overridden) by a derived class. When you refer to a derived class object
using a pointer or a reference to the base class, you can call a virtual function for
that object and execute the derived classâs version of the function.
ďź Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
ďź They are mainly used to achieve Runtime polymorphism.
ďź Functions are declared with a virtual keyword in base class.
ďź The resolving of function call is done at runtime.
38. Rules for Virtual Functions
⢠Virtual functions should be accessed using pointer or reference of base
class type to achieve runtime polymorphism.
⢠The prototype of virtual functions should be the same in the base as well as
derived class.
⢠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.
39. Virtual Function : Example
#include<iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base classn";
}
void show()
{
cout << "show base classn";
}
};
class derived : public base {
public:
void print()
{
cout << "print derived classn";
}
void show()
{
cout << "show derived classn";
}
};
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;
}
40. Pure Virtual Function in C++
⢠Sometimes implementation of all function cannot be provided in a base
class because we donât know the implementation.
⢠For example, let Shape be a base class. We cannot provide implementation
of function draw() in Shape, but we know every derived class must have
implementation of draw().
⢠A pure virtual function (or abstract function) in C++ is a virtual function for
which we donât have an implementation in base class, we only declare it. A
pure virtual function is declared by assigning 0 in the declaration.
⢠We generally override a pure virtual function of base class into its derived
class to provide an implementation.
41. Pure Virtual Function : Example 1
int main()
{
Derived d;
d.fun();
return 0;
}
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() {
x =10;
return x; }
};
// This class inherits from Base and implements fun()
class Derived: public Base
{
int y;
public:
void fun() { cout << âValue of x = â << getX(); }
};
Output:
Value of x = 10
42. Pure Virtual Function : Example 2
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
46. Abstract Class in C++
⢠In C++, A class is abstract if it has at least one pure virtual function.
// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};
In the above example, Test is an abstract class because it has a pure virtual function
show().
47. Abstract Class in C++
⢠An abstract class cannot be instantiated â meaning that we cannot create
objects of abstract class.
// pure virtual functions make
a class abstract
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
int main()
{
Test t;
return 0;
}
48. Abstract Class in C++
⢠Although we cannot have object of abstract class, but we can have pointers
and references of abstract class type.
class Base
{
public:
virtual void show() = 0;
};
class Derived: public Base
{
public:
void show() { cout << "In Derived n"; }
};
int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
49. Abstract Class in C++
⢠If we do not override pure virtual function of base class in its derived class,
then derived class also becomes abstract class.
-- Since Base has a pure virtual
function show(), so it is an abstract
class.
-- We did not override pure virtual
function show() into Derived
class, so it is also abstract class.
-- Clearly, both Base and Derived are
abstract classes here.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base {
// Empty Derived class
};
int main()
{
Derived d;
return 0;
}
50. Summary of Important Points about Abstract Class
1. A class is abstract if it has at least one pure virtual
function.
2. If we do not override the pure virtual function in derived class, then
derived class also becomes abstract class.
3. We cannot create objects of abstract classes.
4. We can create pointers and references of abstract class type.
5. An abstract class can have constructors.
51. What will be the output of the following C++ code?
#include<iostream>
using namespace std;
class Mobile
{
long int contactno;
public:
virtual void getStatus() = 0;
Mobile()
{
contactno=9898989890;
cout<<contactno;
}
};
class Person: public Mobile
{
public:
void getDetails() { cout << âBlockedâ; }
};
int main()
{
Person p;
p.getDetails();
return 0;
}
MCQ
A. 9898989890
B. Blocked
C.9898989890 Blocked
D. Error
52. What will be the output of the following C++ code?
#include<iostream>
using namespace std;
class Mobile
{
long int contactno;
public:
virtual void getStatus() = 0;
Mobile()
{
contactno=9898989890;
cout<<contactno;
}
};
class Person: public Mobile
{
public:
void getStatus(){ cout <<â Blockedâ; }
void getDetails() { cout << â Welcomeâ;
}
};
int main()
{
Person p;
p.getDetails();
return 0;
}
MCQ
A. 9898989890 Welcome
B. Blocked
C.9898989890 Blocked
D. Error
53. Pointer to object
⢠A variable that holds an address value is called a pointer variable.
⢠Just like other pointers, the object pointers are declared by placing in front of a object
pointer's name.
⢠Object can also have an address , so there is also a pointer that can point to the address of
an object. That is known as pointer to an object.
⢠It takes the following general form : class-name â object-pointer ;
Example : class Date
{
};
Date d1;
Date *d2;
d2=&d1;
d2->functions()
object pointer
54. Pointer to object : An Example
#include <iostream>
using namespace std;
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h =
2.0)
{
cout <<"Constructor called." << endl;
length = l; breadth = b; height = h;
}
double Volume()
{
return length * breadth * height;
}
};
int main()
{
Box Box1(3.3, 1.2, 1.5); // Declare box1 object
Box *ptrBox; // Declare pointer to a class.
// Save the address of first object
ptrBox = &Box1;
// Now try to access a member using pointer
cout << "Volume of Box1: " << ptrBox->Volume() <<
endl;
return 0;
}
Output:
55. âthisâ pointer in C++
⢠It can be used to refer to the current class instance/object.
⢠âthisâ keyword represents address of current object of the class.
Syntax:
this-> instance variable=value;
Uses of this pointer:
1) When local variableâs name is same as memberâs
name
2) To return reference to the calling object
56. âthisâ pointer in C++ : Example 1
#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to
retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl;
}
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
57. âthisâ pointer in C++ : Example 2
When a reference to a local object is returned, the returned reference can be used to chain
function calls on a single object.
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) {
this->x = x;
this->y = y;
}
Test& setX(int a) { x = a; return *this; }
Test& setY(int b) { y = b; return *this; }
void print() {
cout << "x = " << x << " y = " << y << endl;
}
};
int main()
{
Test obj1(5, 5);
// Chained function calls.
// All calls modify the same object
// as the same object is returned by
// reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
58. Pointer to derived class
ďA pointer of one class can point to other class, but classes must be a
base and derived class, then it is possible.
ďTo access the variable of the base class, base class pointer will be
used.
59. Pointer to derived class Example
class base{...};
class derived: public base{...};
base b1,*b2;
derive d1;
b2=&d1;
60. What will be the output of the following C++ code?
#include <iostream>
using namespace std;
class mobile
{
public:
void playRingTone()
{
cout<<"mobile ring tone"<<endl;
}
};
class samsung:public mobile
{
void playRingTone()
{
cout<<"samsung ring tone"<<endl;
}
};
class realme:public mobile
{
void playRingTone()
{
cout<<"real me ringtone"<<endl;
}
};
int main()
{
mobile *mptr;
samsung s1;
mptr=&s1;
mptr->playRingTone();
return 0;
}
A. mobile ring tone
B. samsung ring tone
C. real me rington
D. Error