4 - Function - Operator
4 - Function - Operator
INTRODUCTION TO
PROGRAMMING
CSC 1102
MD.NAZMUL HOSSAIN
(UNDERGRADUATE) LECTURER CS, AIUB
Slide-2
Function/Operator Overloading
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading
and operator overloading respectively
An overloaded declaration is a declaration that had been declared with the same
name as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition
(implementation).
When you call an overloaded function, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the
function with the parameter types specified in the definitions. The process of
selecting the most appropriate overloaded function is called overload resolution.
MMH
Slide-3
Function Overloading
#include <iostream> int main(void)
using namespace std; {
class printData printData pd;
{
public: pd.print(5);
void print(int i){ pd.print(500.263);
cout << "Printing int:"<< i << endl; pd.print("Hello C++");
} pd.print(5, 10);
void print(double f) {
cout <<"Printing float: " << f <<endl; return 0;
} }
void print(char* c) { OUTPUT
cout <<"Printing character:"<<c <<endl; Printing int: 5
} Printing float: 500.263
void print(int a, int b){ Printing character: Hello C++
cout << "Printing int:"<< a << b <<endl; Printing int: 5 10
}
MMH
Slide-4
#include<iostream> Function Overriding
using namespace std;
int main()
class BaseClass {
{ BaseClass bs;
public: DerivedClass dr;
void Display()
bs.Display();
{
dr.Display();
cout << "Display method of BaseClass";
} }
};
class DerivedClass : public BaseClass OUTPUT
{ Display method of BaseClass
public: Display method of DerivedClass
void Display()
{
cout << "Display method of DerivedClass";
}
};
MMH
Slide-5
Friend Function
A friend function is a function which can access the private and protected member
of a class outside the scope of that class.
A friend function usually takes objects as parameter.
A friend function can act as a bridge among different classes/objects.
Member function of a class can be friend function of another class.
A class can be friend of another class
The friend of a friend is not considered a friend unless explicitly specified.
The declaration of friend function should be made inside the body of class (can be
anywhere inside class either in private or public section) starting with keyword
friend.
MMH
Slide-6
Similar to friend functions, a friend class is a class whose members have access to
the private or protected members of another class
MMH
Slide-8
MMH
Slide-9
#include <iostream> Friend Class
using namespace std; void Rectangle::convert (Square a)
{
class Square; width = a.side;
class Rectangle { height = a.side;
int width, height; }
public:
int area (){ int main ()
return (width * height); {
} Rectangle r;
void convert (Square a); Square s (4);
}; r.convert(s);
class Square { cout << “Area is” <<r.area();
friend class Rectangle; return 0;
private: }
int side; Output
public: Area is: 16
Square (int a):side(a) {} //constructor
};
MMH
Slide-10
Static Class Member
When we declare a member of a class as static it means no matter how many
objects of the class are created, there is only one copy of the static member.
All static data is initialized to zero when the first object is created, if no other
initialization is present.
We can not put it in the class definition, but it can be initialized outside the class
as done in the following example by re-declaring the static variable, using the scope
resolution operator :: to identify which class it belongs to.
MMH
Slide-11
#include <iostream> Static Data Member
using namespace std;
Initialize
int Box::objectCount = 0; static member
class Box {
public: of class Box
int main()
static int objectCount;
{
Box(double l, double b, double h) {
Box Box1(3.3, 1.2, 1.5);
cout <<"Constructor called." << endl;
Box Box2(8.5, 6.0, 2.0);
length = l;
breadth = b;
// Print total number of objects.
height = h; objectCount increase every cout << “Volume of Box1:”
objectCount++; time object is created
<<Box1.Volume() <<endl;
}
cout << "Total objects: “
double Volume(){
<<Box::objectCount <<endl;
return length * breadth * height;
}
return 0; Output
private:
} Constructor called.
double length;
Constructor called.
double breadth;
Volume of Box 1: 5.94
double height;
Total objects: 2
};
MMH
Slide-12
Static Member Function
A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope resolution
operator ::
A static member function can only access static data member, other static member
functions and any other functions from outside the class.
MMH
Slide-13
Static Member Function
#include <iostream> private:
using namespace std; double length;
double breadth;
class Box { double height;
public: };
static int objectCount;
Box(double l, double b, double h){ int Box::objectCount = 0; //initialize
cout<<"Constructor called"<<endl; int main() {
length = l;
breadth = b; Box Box1(3.3, 1.2, 1.5);
height = h; Box Box2(8.5, 6.0, 2.0);
objectCount++;
} cout <<"Total objects:"
static int getCount() <<Box::getCount();
{ return 0;
Output
return objectCount; }
Constructor called
} Constructor called
Total objects: 2
MMH
Slide-14
#include <iostream> Overloading Unary Operator (++ --)
using namespace std; // overloaded prefix ++ operator
class Time { Time operator++ (){
private: ++minutes; // increment this object
int hours; // 0 to 23 if(minutes >= 60)
int minutes; // 0 to 59 {
++hours;
public: minutes -= 60;
Time(){ }
hours = 0; return Time(hours, minutes); Output
minutes = 0; }
H: 12 M:0
} H: 12 M:1
};
Time(int h, int m) { int main() {
hours = h; Time T1(11, 59);
minutes = m; ++T1; // increment T1
} T1.displayTime(); // display T1
void displayTime(){ ++T1; // increment T1 again
cout<<"H:"<<hours<<"M:" T1.displayTime(); // display T1
<<minutes<<endl; }
} MMH
Slide-15
This Pointer
Every object in C++ has access to its own address through an important pointer
called this pointer.
The this pointer is an implicit parameter to all member functions. Therefore, inside
a member function, this may be used to refer to the invoking object
‘this’ pointer is a constant pointer that holds the memory address of the current
object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
Suppose that you create an object named x of class A, and class A has a non-static
member function f(). If you call the function x.f(), the keyword this in the body
of f() stores the address of x.
MMH
Slide-16
include <iostream> Overloading Binary Operator (+ - * /)
using namespace std; // Overload + operator to add two Box objects.
class Box { Box operator+(Box b){
double length; Box c;
double breadth; c.length = this->length + b.length;
double height; c.breadth = this->breadth + b.breadth;
public: c.height = this->height + b.height;
double getVolume(void) {
// b.length is Box1 (earlier object)
return length * breadth * height;
// this->length is Box2 (current object)
} return c;
void setLength( double l ) { }
length = l; };
} // Main function for the program
void setBreadth( double b ){ int main( ) {
breadth = b; Box Box1; // Declare Box1 of type Box
} Box Box2; // Declare Box2 of type Box
void setHeight( double h ){ Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a
height = h;
box here
}
MMH
Slide-17
// box 1 specification
Overloading Binary Operator (+ - * /)
Box1.setLength(6.0); // Add two object as follows:
Box1.setBreadth(7.0); Box3 = Box1 + Box2; //binary operator
Box1.setHeight(5.0);
// volume of box 3
// box 2 specification volume = Box3.getVolume();
Box2.setLength(12.0); cout << "Volume of Box3:"
Box2.setBreadth(13.0); << volume <<endl;
Box2.setHeight(10.0);
return 0;
// volume of box 1 }
volume = Box1.getVolume();
cout<<"Volume of Box1:"<<volume<<endl;
Output
// volume of box 2 Volume of Box1 : 210
volume = Box2.getVolume(); Volume of Box2 : 1560
cout<<"Volume of Box2:”<<volume<<endl;
Volume of Box3 : 5400
MMH
Slide-18
Dynamic Memory: new & delete Operator
In C++ the new and delete operators provide built-in language support for
dynamic memory allocation and de-allocation.
Many times, you are not aware in advance how much memory you will need to
store particular information in a defined variable and the size of required memory
can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given
type using a special operator in C++ which returns the address of the space
allocated. This operator is called new operator.
If you are not in need of dynamically allocated memory anymore, you can
use delete operator, which de-allocates memory previously allocated by new
operator.
MMH
Slide-19
Dynamic Memory: new & delete Operator
#include <iostream>
using namespace std;
int main ()
{
double *pvalue = new double; // Request memory for the variable