You are on page 1of 27

Object oriented Programming

Lecture: Conversion between data types,


overloading functions, friend functions

Object oriented programming in C++ by Robert Lafore 1


Recap..
• Operator overloading

Object oriented programming in C++ by Robert Lafore 2


Cast operations in c++

int intvar1 = 15; int intvar2 = 2;


float without_cast=intvar1/intvar2;
float with_cast =
static_cast<float>(intvar1)/intvar2;
cout << "without cast: "<<without_cast<<endl;
cout << "with cast: " << with_cast << endl;

Object oriented programming in C++ by Robert Lafore 3


Conversions Between Basic Types
• Two options
• Implicit
• intvar = floatvar; //simply truncate fractional part..no roundoff!
• Explicit
• intvar = int(floatvar);
• Conversions Between Objects and Basic Types
• If s is a class object, when the compiler sees the expression static_cast<char *>(s),
the compiler generates the call to convert the operand s to a char *.

Object oriented programming in C++ by Robert Lafore 4


The different possible data conversion situations are:
1. Conversion between basic and user defined
a) Conversion from basic to user defined data type
b) Conversion from user-defined data type to basic data type
2. Conversion between user defined data types

Object oriented programming in C++ by Robert Lafore 5


1 a) Conversion from basic to user defined data type

Ratio operator =(Ratio r) int main()


{ {
cout << "operator = called" << endl; Ratio rr; int c = 2;
num = r.num; rr = Ratio(c); //or rr=c;
den = r.den; rr.Display();
return *this; return 0;
} }

Ratio(int i)
{
cout << "conversion from basic(int)
to user defined data type occured"
<< endl;
num = i;
den = i;
}

Object oriented programming in C++ by Robert Lafore 6


1 b) Conversion from user-defined data type to basic data type

• Conversion from user-defined type of basic data type is done by overloading the cast operator
of basic type as a member function.
• Operator function is defined as an overloaded basic data type which takes no arguments.
• Return type of operator is not specified because the cast operator function itself specifies the
return type.

class class_name {
...
public:
operator data_type() {
//Conversion code
}
};

Object oriented programming in C++ by Robert Lafore 7


1 b) Conversion from user-defined data type to basic data type

int main()
{
operator int() Ratio rr(4,5); int numerator;
{ numerator = rr;
return num; rr.Display();
} cout << "Numerator: " << numerator;
}

Object oriented programming in C++ by Robert Lafore 8


2. Conversion between user defined data types
class Polar
{
private:
class Cartesian float radius, angle; int main()
{ public: {
Polar()
private: Polar pol(10.0, 0.78);
{
float xco, yco; radius = 0;
Cartesian cart;
public: angle = 0; cart = pol;
Cartesian() } cout << "\nGiven Polar: ";
{ Polar(float rad, float ang) pol.display();
xco = 0; { cout << "\nEquivalent cartesian: ";
yco = 0; radius = rad; cart.display();
} angle = ang; return 0;
Cartesian(float x, float y) } }
{
xco = x; operator Cartesian()
yco = y; {
} float x = static_cast<int>(radius * cos(angle));
float y = static_cast<int>(radius * sin(angle));
void display()
return Cartesian(x, y);
{ }
cout << "(" << xco << "," << yco void display()
<< ")"; {
} cout << "(" << radius << "," << angle << ")";
}; }
};

Object oriented programming in C++ by Robert Lafore 9


Revisiting operator overloading: overloading the overloaded operator

Ratio operator +(Ratio r2) int main()


{ {
num = num + r2.num;
den = den + r2.den; Ratio r1(1, 0), r2(1, 5),r3; int c = 2;
return *this; r3=r1 + r2;
} r3.Display();
Ratio operator +(int n) r3=r1 + c;
{ r3.Display();
num = num + n; return 0;
den = den + n; }
return *this;
}

Object oriented programming in C++ by Robert Lafore 10


Comparison operator (object > int)

bool operator > (int n) int main()


{ {
cout << "int version" << endl;
if (num > n) Ratio r1(1, 0), r2(1, 5),r3; int c = 2;
return true; if (r1 > 4)
else cout << "r1 is greater " << endl;
return false; else
} cout << "r1 is smaller " << endl;
bool operator >(Ratio r)
{ return 0;
cout << "bool version" << endl; }
if (num > r.num)
return true;
else
return false;
}

Object oriented programming in C++ by Robert Lafore 11


Comparison operator (int > object)
bool operator > (int n)
{
cout << "int version" << endl; int main()
if (num > n) {
return true;
else Ratio r1(1, 0), r2(1, 5),r3; int c = 2;
return false; if (4 > r1)
} cout << "r1 is greater " << endl;
operator int() else
{ cout << "r1 is smaller " << endl;
cout << "operator cast: " << endl;
return 5; return 0;
} }
bool operator >(Ratio r)
{
cout << "bool version" << endl;
if (num > r.num)
return true;
else
return false;
}

Object oriented programming in C++ by Robert Lafore 12


Copy elision
• compiler optimization technique that avoids unnecessary copying of objects
class B
{
public:
int num;
public:
B()
{
cout << "Default called" << endl;
}
B(int num) //default constructor
{
cout << "Parameterized Constructor called" << endl; int main()
} {
B(const B& b) //copy constructor B ob = 2;
{ }
cout << "Copy constructor called" << endl;
}
};

Object oriented programming in C++ by Robert Lafore 13


Why copy constructor is not called?
• According to theory, when the object “ob” is being constructed, one argument
constructor is used to convert “copy me” to a temporary object & that temporary object
is copied to the object “ob”. So the statement
B ob = 2;
should be broken down by the compiler as
B ob = B(2);
• However, most of the C++ compilers avoid such overheads of creating a temporary
object & then copying it.
• The modern compilers break down the statement
B ob = 2; //copy initialization
as
B ob(2); //direct initialization
• and thus eliding call to copy constructor.

Object oriented programming in C++ by Robert Lafore 14


Contd..
• There are two major cases where copy elision would happen: returning a local
variable inside a function, and initializing a variable with a temporary value.
• Return a local variables
string dosth() {
string local_str;
// Some operations on local_str.
return local_str;
}
• string out_str = dosth();
• Some people prefer to create a function and return a pointer rather than a value,
thinking that return a large object is expensive, because it invokes object copy.
• However, thanks to copy elision, the out_str will take the ownership of the local
variable right after the function exits, it’s completely free.
Object oriented programming in C++ by Robert Lafore 15
Contd..
SomeBigObject BuildBigObject(){
SomeBigObject foo;
// Initialize foo...
return foo;
}
SomeBigObject bar = BuildBigObject();

• For bar to be initialized, the function-scoped foo has to be copied from the function’s stack frame into the outer-
scoped bar variable, an expensive copy. What if there was a way for bar to just become the function-scoped foo
(i.e. whenever foo is used, just use bar instead?).
• Remember that the return value of BuildBigObject is a temporary rvalue. It will disappear when
BuildBigObject's stack frame is popped. The compiler can detect that foo is a temporary and instead of
discarding it, it will make bar and foo refer to the same memory location in the invocation of BuildBigObject.
That means that when BuildBigOjbect is initializing foo, it is actually doing work on the outer-scoped bar.

Object oriented programming in C++ by Robert Lafore 16


Void pointer
• The void pointer, also known as the generic pointer, is a special type of pointer
that can be pointed at objects of any data type!

int nValue;
float fValue;

void *ptr;
ptr = &nValue; // valid
ptr = &fValue; // valid

Object oriented programming in C++ by Robert Lafore 17


int value = 5;
void *voidPtr = &value;

//cout << *voidPtr << endl; // illegal: cannot dereference a void pointer

int *intPtr = static_cast<int*>(voidPtr); // however, if we cast our void poin


ter to an int pointer...

cout << *intPtr << endl; // then we can dereference it like normal

Object oriented programming in C++ by Robert Lafore 18


Friend functions
• Encapsulation and data hiding are two primary features of object-oriented programs.
• You use encapsulation when you place data and functions together in a capsule as
objects.
• You use data hiding when you create private class members; they remain inaccessible to
functions that are not part of the class.
• Sometimes, however, it is convenient to allow an outside, nonmember function to have
access to a private data member
• Problems:
• If the function is a member of the first class, it doesn’t have access to the data in the
second class;
• if the function is a member of the second class, it doesn’t have access to the data in the
first.
• Solution: create special functions called friend functions

Object oriented programming in C++ by Robert Lafore 19


What is a friend function and friend class?
• A friend function is a function that can access the non-public members of a class,
even though the function itself is not a member of the class.
• A friend function is a normal function with special access privileges.
• In addition to friend functions, you can create friend classes. A friend class is a
class in which every function can access non-public members of another class; in
other words, every function in a friend class is a friend function.
• When you create a class, you must declare the names of the functions you will
allow to be friends of your class.

Object oriented programming in C++ by Robert Lafore 20


HOW TO DECLARE A FUNCTION AS A FRIEND
• class named Customer that can be used by a business to hold a customer number
and the balance owed
class Customer void Customer::displayCustomer() int main()
{ { {
friend void cout << "In the member function" << endl; Customer c(1, 200);
cout << "Customer #" << custNum << c.displayCustomer();
displayAsAFriend(Customer); displayAsAFriend(c);
" has a balance of $" << balanceDue << endl;
private:
}
int custNum; void displayAsAFriend(Customer cust) return 0;
double balanceDue; { }
public: cout << "In the friend function:" << endl;
Customer(int = 0, double = 0.0); cout << "Customer #" << cust.custNum <<
void displayCustomer(); " has a balance of $" <<
}; cust.balanceDue << endl;
}
Customer::Customer(int num, double
balance)
{
custNum = num;
balanceDue = balance;
}

Object oriented programming in C++ by Robert Lafore 21


Member functions vs friend functions
• You can declare friend function at any point (at the start of class, below public
identifier, below private identifier). Whereas, member functions can only be be
declared below public identifier..e.g.
class Customer
{

private:
int custNum;
double balanceDue;
void displayCustomer(); function "Customer::displayCustomer" is inaccessible
friend void displayAsAFriend(Customer);

public:
Customer(int = 0, double = 0.0);

};
Object oriented programming in C++ by Robert Lafore 22
Contd..
• Member functions will have the access on its own private variables and some
public variables of other classes but a friend function will have the accessibility on
private variable of other classes too.
class beta; //needed for frifunc class beta
declaration {
private: int main()
class alpha
int data; {
{
public: alpha aa;
private:
beta() : data(7) { } beta bb;
int data;
friend int frifunc(alpha, beta); //friend function cout << frifunc(aa, bb) << endl;
public:
}; return 0;
alpha() : data(3) { }
int frifunc(alpha a, beta b) //function definition }
friend int frifunc(alpha, beta); //friend
function {
}; return( a.data + b.data );
}

Object oriented programming in C++ by Robert Lafore 23


Contd..
• Member functions require class name Customer and the scope resolution
operator in the function whereas this is not the case with friend functions.
• Member function does not involve friend keyword in its declaration whereas
friend functions do involve that keyword.

Object oriented programming in C++ by Robert Lafore 24


Friend class (example)
class alpha
{
private: int main()
int data1; {
public: alpha a;
alpha() : data1(99) { } //constructor beta b;
friend class beta; //beta is a friend class b.func1(a);
}; b.func2(a);
cout << endl;
class beta
return 0;
{
}
public: //access private alpha data
void func1(alpha a) { cout << “\ndata1 = ” <<
a.data1; }
void func2(alpha a) { cout << “\ndata1 = ” <<
a.data1; }
};
Object oriented programming in C++ by Robert Lafore 25
Recommended reads
• Page 520-529 (Friend functions), Chapter 11, Object oriented programming in
C++ by Robert Lafore
• Page 410, section 9.12: Friend functions and friend classes, Dietal and Dietal

Object oriented programming in C++ by Robert Lafore 26


That’s it

Object oriented programming in C++ by Robert Lafore 27

You might also like