M2Part2 (Friend Function) (6 Files Merged)
M2Part2 (Friend Function) (6 Files Merged)
Programming using C+
[TCS-307]
Friend
function
Friend
Class
Friend Function
• A friend function is a function that can access the private members of a class as
though it were a member of that class.
4
Declaration of friend function in C++
6
Properties
7
Properties
A friend function is not A friend function cannot access A friend function can
invoked using the class the private and protected data be a global function or
object as it is not in the members of the class directly. It a member of another
scope of the class. needs to make use of a class class.
object and then access the
members using the dot operator.
8
Example
9
Example
class Box { void printWidth( Box box )
{
double width;
public: /* Because printWidth() is a friend of Box, it can
void setWidth( double wid ); directly access any member of this class */
friend void printWidth( Box box );
cout << "Width of box : " << box.width <<endl;
};
}
void Box::setWidth( double wid ) int main( )
{
{
Box box;
width = wid; box.setWidth(10.0);
} printWidth( box );
return 0;
10 }
Friend Function accessing members of Two Different
Class
#include<iostream> class ClassB {
using namespace std;
int main( ) {
# forward declaration private: ClassA objectA;
int numB; ClassB objectB;
class ClassB;
public: cout << "Sum: =" << add(objectA,
class ClassA { ClassB( ) objectB);
private: { return 0;
int numA; numB=12; }
}
public:
friend int add(ClassA, ClassB);
ClassA() };
{ int add(ClassA objectA, ClassB objectB)
numA=12; } {
return (objectA.numA + objectB.numB);
friend int add(ClassA, ClassB); }
};
Example
#include <iostream>
using namespace std;
int main()
class XYZ
{
{ XYZ obj;
private: int num=100; char ch='Z'; disp(obj); return 0;
public: friend void disp(XYZ obj); }
};
• Friend class can access private and protected members of the class to which it is a
friend.
• Friend of one class can be friend of another class or all the classes in one program,
such a friend is known as GLOBAL FRIEND.
• Friend can access the private or protected members of the class in which they are
declared to be friend, but they can use the members for a specific object.
13
Friend Class
• Friends, can be friend of more than one class, hence they can be used for message
passing between the classes.
• Friend can be declared anywhere (in public, protected or private section) in the
class.
• If Base class is a friend of class X, subclass Derived is not a friend of class X; and if
class X is a friend of class Base, class X is not a friend of subclass Derived.
14
Friend Class
class A{
……
friend class B;
};
class B
{ ……..
};
• B is a friend of class A. So class B can access the private and protected
members of class A.
• But this does not mean that class A can access private and protected members
of the class B. Note that the friendship is not mutual unless we make it so.
15
Example
class ABC
#include <iostream>
{
using namespace std;
public: void disp(XYZ obj)
class XYZ
{
{
cout<<obj.ch<<endl;
private: char ch='A'; cout<<obj.num<<endl;
int num = 11; }
friend class ABC; };
}; int main()
{
ABC obj; XYZ obj2;
obj.disp(obj2);
return 0; }
16
Example
using namespace std; class printClass
class Area{ {
int length , breadth , area; public:
public: void printArea(Area a){
Area(int len, int bre) cout<<"Area = "<<a.area;
{ }
length=len; };
breadth=bre; int main(){
} Area a(10,15);
void calcArea(){ a.calcArea();
area = length * breadth; printClass p;
} p.printArea(a);
friend class printClass; return 0;
}; }
Advantages
• You can use a friend function to bridge two classes by operating objects of two
different classes.
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
21
Object Oriented
Programming using C+
[TCS-307]
auto/static variable
global variable
inline Function
auto/static variable
int main() int main()
{
{
show();
show(); show();
show(); show(); O/P: 11
show(); return 0; 12
return 0; } 13
void show()
}
{
void show() O/P: 11 static int a=10; //static variable
{ 11 a++;
int a=10; //auto variable 11 printf("\n %d",a);
a++; }
printf("\n %d",a);
}
Extern or global variable
int a=10; //extern or global variable, printf("\n %d",a);
can be accessed by all the functions
}
int main()
void fun2()
{
{
fun1();
a++;
fun2();
printf("\n %d",a);
fun2();
}
fun1();
return 0;
O/P: 9
}
10
void fun1()
11
{
a--;
10
Static/auto variable
Preserve their value even after they are Do not preserve their value even after they
out of their scope. are out of their scope
5
Inline Function
• During a program when a function call was made, CPU stores the memory address of the
instruction following the function call.
• This can become overhead if the execution time of function is less than the switching time
from the caller function to called function.
• A command for the compiler to substitute the call for a function by it‘s implementation =
inline expansion.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t
exist in function body.
The above style is considered as a bad programming style. The best programming style is to just write the
prototype of function inside the class and specify it as an inline in the function definition.
Example
#include <iostream>
using namespace std;
Output
inline int Max(int x, int y) {
Max (20,10): 20
return (x > y)? x : y; }
// Main function for the program
Max (0,200): 200
Disadvantages
• Compiler decides in general itself which functions to inline.
11
References
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
13
Object Oriented
Programming using C+
[TCS-307]
Constructor
Types of Constructor
Destructor
Constructor
• Constructor is a special method which is invoked automatically at the
time of object creation.
• Default constructor
• Parameterized constructor
• Copy Constructor
Constructor
class Test
{
public:
// create a constructor
Test()
{
// code
}
};
Default Constructor
• copy constructor is a member function that initializes an object using another object of
the same class.
If we don’t define our own copy constructor, the C++ compiler creates a default copy
constructor for each class which does a member-wise copy between objects.
We need to define our own copy constructor only if an object has pointers or any
runtime allocation of the resource like file handle, a network connection etc.
9
Copy Constructor/Assignment Operator
• Copy constructor is called when a new object is created from an existing object,
as a copy of the existing object.
• In the above example (1) calls copy constructor and (2) calls assignment
operator.
10
Copy Constructor
We cam make a copy constructor as private. When we make a copy constructor private
in a class, objects of that class become non-copyable. This is particularly useful when
our class has pointers or dynamically allocated resources.
A copy constructor is called when an object is passed by value. Copy constructor itself
is a function. So if we pass an argument by value in a copy constructor, a call to copy
constructor would be made to call copy constructor which becomes a non-terminating
chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.
One reason for passing const reference is, we should use const in C++ wherever
possible so that objects are not accidentally modified.
11
Destructor
A destructor is defined like constructor. It must have same name as class. But it is
prefixed with tilde sign (~). C++ destructor cannot have parameters.
12
References
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
14
Object Oriented
Programming using C+
[TCS-307]
In C++, most of operators can be overloaded so that they can perform special
operations relative to the classes you create.
• After overloading the appropriate operators, you can use objects in expressions in just the
same way you use C++'s built-in data types.
• Operators come in three flavours:
Unary Operators : ++,--
Binary Operators : + , * , /
Ternary Operators : ? :
You are free to overload most of the built-in operators, but you cannot create new operators of
your own.
You can overload these operators to do anything you want, but it is a good programming
practice for them to make sense.
That means you can have the ++ operator to decrement, but it would make no sense to do so.
Operator Overloading
C++ operators that can be overloaded
Operators that are overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
. .* :: ?: sizeof
6
Operator Overloading
You can overload virtually any c++ operator, but you cannot create your own
set of operators.
You cannot alter the pre-defined job performed by any operator, that means you cannot
overload + operator in such a way to perform subtraction of two integers.
5
operator Function
Operators are overloaded by creating operator functions.
An operator function defines the operations that the overloaded operator will
perform relative to the class upon which it will work.
The way operator functions are written differs between member and non-member
functions.
Member operator Function
A member operator function for binary operators
Return Type/ Class-Name operator # ( argument -list )
{
// operations
}
Often, operator functions returns an object of the class they operate on, but return-type
can be any valid type.
The # is a placeholder. When you create an operator function, substitute the operator for
the #.
While overloading binary operators using member function, the argument-list will contain
at least one parameter.
Operator Overloading
class className
{ ... .. ...
public:
returnType operator symbol (arguments)
{ ... .. ...
}
... .. ...
};
Unary Operator Overloading
class Distance void operator - ( )
{ {
public: feet = - feet ;
int feet, inch; inch = - inch ;
Distance(int f, int i) cout << ” \n “<< feet << ” “<< inch;
{ }
feet = f; };
int main ( )
inch = i;
{
} Distance d1(8, 9);
-d1; //operator obj;
return 0 ;
}
9
Unary Operator Overloading
// Overload ++ when used as prefix
// Overload ++ when used as prefix
#include <iostream> void operator ++ ( )
using namespace std; {
class Count ++value;
{ }
private: void display( )
int value; {
cout << "Count: " << value << endl;
public:
}
// Constructor to initialize count to 5 };
Count( )
{ int main()
value=5; {
} Count count1;
// Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
} 10
Unary Operator Overloading using Friend Function
11
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.
class Distance {
public: Distance Operator + (Distance &d2)
{
int feet, inch;
Distance d3;
Distance() d3.feet = feet + d2.feet;
{ d3.inch = inch + d2.inch;
feet = 0; return d3;
inch = 0; }
} };
Distance(int f, int i)
{
feet = f;
inch = i;
} 12
Binary Operator Overloading using member function
Binary Operator Overloading using friend
function
• In this approach, the operator overloading function must precede with friend
keyword, and declare a function class scope.
class Distance {
public: Distance operator+(Distance& d1, Distance& d2)
int feet, inch; {
Distance() Distance d3;
{ d3.feet = d1.feet + d2.feet;
feet = 0; d3.inch = d1.inch + d2.inch;
inch = 0; return d3;
} } int main()
Distance(int f, int i) {
{ Distance d4(8, 9);
feet = f; Distance d5(10, 2);
inch = i; Distance d6;
} d6 = d4 + d5;
cout << ”\n" << d6.feet;
friend Distance operator+(Distance&, Distance&); cout << d6.inch;
}; return 0;
}
References
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
17
Object Oriented
Programming using C+
[TCS-307]
In C++, most of operators can be overloaded so that they can perform special
operations relative to the classes you create.
You are free to overload most of the built-in operators, but you cannot create new
operators of your own.
After overloading the appropriate operators, you can use objects in expressions in just the
same way you use C++'s built-in data types.
You can overload these operators to do anything you want, but it is a good programming
practice for them to make sense.
That means you can have the ++ operator to decrement, but it would make no sense to do
so.
You cannot change any operator's precedence.
You cannot change syntax to use an operator.
Operator Overloading
C++ operators that can be overloaded
Operators that are overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
. .* :: ?: sizeof
6
operator Function
Operators are overloaded by creating operator function.
An operator function defines the operations that the overloaded operator will
perform relative to the class upon which it will work.
The way operator functions are written differs between member and non-member
functions.
Member operator Function
A member operator function for binary operators
Return Type/ Class-Name operator # ( argument -list )
{
// operations
}
Often, operator functions returns an object of the class they operate on, but return-
type can be any valid type.
The # is a placeholder. When you create an operator function, substitute the
operator for the #.
In unary operator function, no arguments should be passed.
While overloading binary operators using member function, the argument-list will
contain at least one parameter.
Operator Overloading
class className
{ ... .. ...
public:
returnType operator symbol (arguments)
{ ... .. ...
}
... .. ...
};
Unary Operator Overloading
class Distance void operator - ( )
{ {
public: feet = - feet ;
int feet, inch; inch = - inch ;
Distance(int f, int i) cout << ” \n “<< feet << ” “<< inch;
{ }
feet = f; };
int main ( )
inch = i;
{
} Distance d1(8, 9);
-d1; //operator obj;
return 0 ;
}
8
Unary Operator Overloading
// Overload ++ when used as prefix
// Overload ++ when used as prefix
#include <iostream> void operator ++ ( )
using namespace std; {
class Count ++value;
{ }
private: void display( )
int value; {
cout << "Count: " << value << endl;
public:
}
};
Count( )
{ int main()
value=5; {
} Count count1;
// Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
} 9
Unary Operator Overloading using Friend Function
10
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.
class Distance { Distance Operator + (Distance &d2) int main()
public: { {
int feet, inch; Distance d(5,6);
Distance d3;
Distance d1(6,2);
Distance() d3.feet = feet + d2.feet; Distance d3=d+d1;
{ d3.inch = inch + d2.inch; cout<<d3.feet<<"feet"<<d3.inch<<"inch";
feet = 0; return d3; return 0;}
inch = 0; }
} };
Distance(int f, int i)
{
feet = f;
inch = i;
}
11
Binary Operator Overloading using member function
Binary Operator Overloading using friend
function
• In this approach, the operator overloading function must precede with friend
keyword, and declare a function class scope.
class Distance {
public: Distance operator+(Distance& d1, Distance& d2)
int feet, inch; {
Distance() Distance d3;
{ d3.feet = d1.feet + d2.feet;
feet = 0; d3.inch = d1.inch + d2.inch;
inch = 0; return d3;
} } int main()
Distance(int f, int i) {
{ Distance d4(8, 9);
feet = f; Distance d5(10, 2);
inch = i; Distance d6;
} d6 = d4 + d5;
cout << ”\n" << d6.feet;
friend Distance operator+(Distance&, Distance&); cout << d6.inch;
}; return 0;
}
References
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
16
Object Oriented
Programming using C+
[TCS-307]
• Like array of other user-defined data types, an array of type class can also be created.
• The array of type class contains the objects of the class as its individual elements.
• An array of objects is declared in the same way as an array of any built-in data type.
class Test
int main()
{
{
private:
// Initializing 3 array Objects with function calls of parameterized constructor as
int x, y;
elements of that array
public:
Test(int cx, int cy)
Test obj[ ] = { Test(1, 1), Test(2, 2), Test(3, 3) };
{
x = cx;
// using add method for each of three elements.
y = cy;
}
for (int i = 0; i < 3; i++)
void add( )
{
{
obj[i].add();
cout << x + y << endl; }
}
};
return 0;
}
Dynamic Memory
Memory in your C++ program is divided into two parts −
The stack − All variables declared inside the function will take up memory from the stack.
The heap − This is unused memory of the program and can be used to allocate the
memory dynamically when program runs.
new and delete Operators: In C++, dynamic memory allocation is done by using the new and delete
operators.
new data-type;
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. The main advantage of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is prime purpose of C++.
8
Dynamic Memory
At any point, when you feel a variable that has been
dynamically allocated is not anymore required, you can free Unlike C’s dynamic memory allocation and
up the memory that it occupies in the free store with the
‘delete’ operator as follows − deallocation functions, new and delete in C++
are operators and are a part of the list of keywords
delete pvalue; used in C++.
#include <iostream>
using namespace std;
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
Dynamic Memory
In C and C++, dynamic memory is allocated in the heap area and gets a pointer returned to
the object created. C++ is stricter in the construction norms. C++ never gives the memory
of the allocated element direct access to initialize, but a constructor is used instead so as
to ensure that:
• Initialization is guaranteed.
• There is no accidental access to an uninitialized object.
• A wrong sized object can’t be returned.
C++ performs twin functions—it dynamically allocates the memory and also invokes the
constructor for proper initialization.
The cleanup procedure with the delete operator also automatically calls the destructor. 10
Dynamic Objects/New Operator
The new operator allocates the exact amount of memory required by the object during
execution.
The allocation is performed on the free memory area, called the heap, assigned to each and
every program especially for the purpose of dynamic memory allocation. The allocation, if
successful by using the new operator, returns a pointer to the object; if it fails,
a bad_alloc exception is raised.
However, on success we can access the object via pointer returned by the new operator.
IntArray *intArray = new IntArray(10);
MyClass *obj = MyClass;
https://www.codeguru.com/cplusplus/what-is-dynamic-object-creation-in-c-c/
this Pointer
In C++, each object of a class gets its own copy of data members and all objects share a single
copy of member functions.
The question comes that is that if only one copy of each member function exists and is used by
multiple objects, how are the proper data members are accessed and updated?
The compiler supplies an implicit pointer along with the names of the functions as ‘this’.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is
available as a local variable within the body of all nonstatic functions.
‘this’ pointer is not available in static member functions as static member functions can be
called without any object (with class name).
this Pointer
When local variable’s name is same as 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' int main()
this->x = x; {
} Test obj;
void print() int x = 20;
{ obj.setX(x);
cout << "x = " << x << endl; obj.print();
} return 0;
}; }
this Pointer
To return reference to the calling object
Test& Test::func ()
{
// statements…..
return *this;
}
this Pointer
When a reference to a local object is returned, the returned reference can be
used to chain function calls on a single object.
class Test Test &setY(int b)
{ {
private: y = b; return *this;
int x; }
int y; void print() { cout << "x = " << x << " y = " << y << endl; }
public: };
Test(int x = 0, int y = 0)
{ int main()
this->x = x; {
this->y = y; Test obj1(5, 5);
} // Chained function calls. All calls modify the same object as the same object is
Test &setX(int a) returned by reference
{ obj1.setX(10).setY(20); obj1.print();
x = a; return 0;
return *this; }
}
References
Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.
18