0% found this document useful (0 votes)
21 views99 pages

M2Part2 (Friend Function) (6 Files Merged)

The document discusses auto/static variables, global variables, and inline functions in C++. It provides examples of using auto variables, static variables, and global/extern variables. It shows that auto variables are reinitialized each time a function is called while static variables retain their value between calls. It also demonstrates that global/extern variables can be accessed across multiple files in a program.

Uploaded by

Hahhaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views99 pages

M2Part2 (Friend Function) (6 Files Merged)

The document discusses auto/static variables, global variables, and inline functions in C++. It provides examples of using auto variables, static variables, and global/extern variables. It shows that auto variables are reinitialized each time a function is called while static variables retain their value between calls. It also demonstrates that global/extern variables can be accessed across multiple files in a program.

Uploaded by

Hahhaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Object Oriented

Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Table of Contents

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.

• To declare a function as a friend of a class, precede the function prototype in the


class definition with the keyword friend.

• To make a function as a friend of a class, it is declared prototype inside the class


either in private or in public section with keyword friend.
Declaration of Friend function in C++

• We can define the friend function as a normal


function to access the data of the class.

4
Declaration of friend function in C++

No friend keyword is used in the definition.


5
Example

6
Properties

A friend function can be It can be called like a A friend function is


declared in the private or normal function without not in the scope of
public section of the class. using the object. the class, of which it
is a friend.

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

class sample{ //friend function definition


int length, breadth; void calcArea(sample s)
{
public:
cout<<"Area = "<<s.length * s.breadth;
sample(int len, int bre) }
{
length=len,breadth=bre; int main()
{ sample s1(10,15);
}
calcArea(s1);
friend void calcArea(sample s); return 0;
//friend function declaration }
};

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); }

};

void disp(XYZ obj)


{
cout<<obj.num<<endl; cout<<obj.ch<<endl;
}
12
Friend Class

• Friend class can access private and protected members of the class to which it is a
friend.

• Friend of the class can be member of some other class.

• 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 are non-members hence do not get “this” pointer.

• 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

• A friend function is used to access all the non-public members of a class.

• You can use a friend function to bridge two classes by operating objects of two
different classes.

• It increases the versatility of overloading operators.

• You may declare a member function of a class as a friend of another class.

• It works symmetrically with all its friends.


Practice Question

1. WAP in C++ to find factorial of a number using friend function.

2. WAP in C++ to get details of students(roll no, name, 3 subject marks) in


getdata( ) member function of class Student and make a friend function
display ( ) to display the result of student.
References

Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

21
Object Oriented
Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Table of Contents

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

static variables auto variables


remains in memory while the program destroyed when a function call where the
is running variable was declared is over.

Preserve their value even after they are Do not preserve their value even after they
out of their scope. are out of their scope

Default value is zero. Default value is garbage value.

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.

• C++ provides an inline functions to reduce the function call overhead.

• A command for the compiler to substitute the call for a function by it‘s implementation =
inline expansion.

• Compiler decides if function is substituted or executed.


Inline Function

Compiler may not perform inline in such circumstances like:

1) If a function contains a loop. (for, while, do-while)

2) If a function contains static variables.

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.

5) If a function contains switch or goto statement.


Inline Function
Example:
class S
{
public:
inline int square(int s) // redundant use of inline
{
// this function is automatically inline
// 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

int main() Max (100,1010): 1010


{ cout << "Max (20,10): " << Max(20,10) <<
endl;
cout << "Max (0,200): " << Max(0,200) <<
endl;
cout << "Max (100,1010): " <<
Max(100,1010) << endl;
return 0; } 9
Example
#include <iostream>
inline void operation :: sum( )
using namespace std;
{
class operation
add = a+b;
{
cout << "Addition of two numbers: " << a+b << "\n";
int a,b, add, sub, mul;
}
float div;
int main()
public:
{
void get(); void sum();
cout << "Program using inline function\n";
};
operation s;
inline void operation :: get( )
s.get();
{ cout << "Enter first value:";
s.sum();
cin >> a;
return 0;
cout << "Enter second value:";
}
cin >> b; } 10
Inline Function
Advantages
Faster than ordinary function call

Disadvantages
• Compiler decides in general itself which functions to inline.

• inline is a recommendation for the compiler.

• Does not always result in gain in speed.

11
References

Herbert Schildt, “C++: The Complete Reference, 4th Edition”, McGraw Hill
Education.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

13
Object Oriented
Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Assistant Professor
Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Table of Contents

Constructor

Types of Constructor

Destructor
Constructor
• Constructor is a special method which is invoked automatically at the
time of object creation.

• It is used to initialize the data members of new object generally.

• The constructor in C++ has the same name as class.

• Default constructor

• Parameterized constructor

• Copy Constructor
Constructor

class Test
{
public:

// create a constructor
Test()
{
// code
}
};
Default Constructor

• A constructor which has no argument is known as default constructor. It is


invoked at the time of creating object.
include <iostream> int main(void)
using namespace std; {
Employee e1; //creating an object of Employee
class Employee
Employee e2;
{ return 0;
public: }
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
} };
5
Parameterized Constructor

• A constructor which has parameters is called parameterized constructor.


• It is used to provide different values to distinct objects.
void display()
#include <iostream> {
using namespace std; cout<<id<<" "<<name<<" "<<salary<<endl;
class Employee { }
public: };
int id;
string name; int main(void)
float salary; {
Employee(int i, string n, float s) Employee e1(101, "Sonoo", 890000);
{ Employee e2(102, "Nakul", 59000);
id = i; e1.display();
name = n; e2.display();
salary = s; return 0;
} }
Copy Constructor

• copy constructor is a member function that initializes an object using another object of
the same class.

ClassName (const ClassName &old_obj);


Copy Constructor
class Point
int getX( ) { return x; }
{ int getY( ) { return y; }
private: };
int x, y;
int main()
public: {
Point(int x1, int y1) { Point p1(10, 15); // Parameterized constructor is called
Point p2 (p1); // Copy constructor is called
x = x1; y = y1;
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
} cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
// Copy constructor
Point(const Point &p1) return 0;
}
{
x = p1.x; y = p1.y;
}
Example

Need of user-defined copy constructor

 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

MyClass t1, t2;


MyClass t3 = t1; ………………………..(1)
t2 = t1; ---------------------(2)

• Copy constructor is called when a new object is created from an existing object,
as a copy of the existing object.

• Assignment operator is called when an already initialized object is assigned a


new value from another 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 works opposite to constructor. It destructs the objects of classes. It can be


defined only once in a class. Like constructors, it is invoked automatically.

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.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

14
Object Oriented
Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Assistant Professor
Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Operator Overloading
 One of C++’s great features is its extensibility; Operator Overloading is
major functionality related to extensibility.

 In C++, most of operators can be overloaded so that they can perform special
operations relative to the classes you create.

 In simple words, overloading an operator means assigning additional


operation or job to it; relative to a specific class (user defined type).

 For example, + operator can be overloaded to perform an operation of string


concatenation along with its pre-defined job of adding two numeric values.

 When an operator is overloaded, none of its original meaning will be lost.


Operator Overloading

• 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

+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++

-- ->* , -> [] () new delete

C++ Operators that cannot be overloaded

Operators that cannot be overloaded

. .* :: ?: sizeof

6
Operator Overloading

 You can overload virtually any c++ operator, but you cannot create your own
set of operators.

 You cannot change any operator's precedence.

 You cannot change syntax to use an operator.

 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.

 An operator function is created using the keyword operator

 Operator functions can be either


 Member function of a class or
 Non-member function (Mostly Friend Functions)

 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 ;
}

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

class Distance void operator - ( Distance &D)


{ {
public: D . feet = - D . feet ;
int feet, inch; D . inch = - D . inch ;
cout << ” \n “<< D . feet << ” “<< D . inch;
Distance(int f, int i)
}
{
feet = f; int main ( )
inch = i; {
} Distance d1(8, 9);
friend void operator - ( Distance &D) ; - d1;
}; return 0 ;
}

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.

• Keeping in mind, friend operator function takes two parameters in a binary


operator, varies one parameter in a unary operator.
Binary Operator Overloading using friend
function

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.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

17
Object Oriented
Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Assistant Professor
Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Operator Overloading

 One of C++’s great features is its extensibility; Operator Overloading is major


functionality related to extensibility.

 In C++, most of operators can be overloaded so that they can perform special
operations relative to the classes you create.

 In simple words, overloading an operator means assigning additional operation or


job to it; relative to a specific class (user defined type).

 For example, + operator can be overloaded to perform an operation of string


concatenation along with its pre-defined job of adding two numeric values.

 When an operator is overloaded, none of its original meaning will be lost.


Operator Overloading

 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

+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++

-- ->* , -> [] () new delete

C++ Operators that cannot be overloaded

Operators that cannot be 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.

 An operator function is created using the keyword operator

 Operator functions can be either


 Member function of a class or
 Non-member function (Mostly Friend Functions)

 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

class Distance void operator - ( Distance &D)


{ {
public: D . feet = - D . feet ;
int feet, inch; D . inch = - D . inch ;
cout << ” \n “<< D . feet << ” “<< D . inch;
Distance(int f, int i)
}
{
feet = f; int main ( )
inch = i; {
} Distance d1(8, 9);
friend void operator - ( Distance &D) ; - d1;
}; return 0 ;
}

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.

• Keeping in mind, friend operator function takes two parameters in a binary


operator, varies one parameter in a unary operator.
Binary Operator Overloading using friend
function

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.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

16
Object Oriented
Programming using C+
[TCS-307]

Dr. Jyoti Agarwal


Dept. of Computer Science & Engineering
Graphic Era Deemed to be University
Dehradun, India
Passing Object as Argument

• In C++, objects can be passed as arguments and can be returned from a


function the same way we pass and return other variables.

Passing Object as Argument


• To pass an object as an argument , write the object name as the argument
while calling the function the same way we do it for other variables.
function_name(object_name);
Returning Object as Argument
object = return object_name;
// print member variables of Student
class Student cout << "Marks 1 = " << student.marks1 << endl;
{ cout << "Marks 2 = " << student.marks2 << endl;
public:
double marks1, marks2; return student;
}; }

// function that returns object of Student int main()


Student createStudent( ) {
{ Student student1;
Student student;
// Call function
// Initialize member variables of Student student1 = createStudent();
student.marks1 = 96.5;
student.marks2 = 75.0; return 0;
}
Passing/Returning Object
class Example {
public: cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a << ",
int a; \nobject 3: " << E3.a<< "\n";
Example add(Example Ea, Example Eb)
{ // Passing object as an argument to function add()
Example Ec;
Ec.a = Ea.a + Eb.a; E3 = E3.add(E1, E2);
return Ec;
} // Changed values after passing object as an argument
}; cout << "New values \n";
int main() cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a<< ",
{ \nobject 3: " << E3.a<< "\n";
Example E1, E2, E3;
// Values are initialized for both objects return 0;
E1.a = 50; }
E2.a = 100;
E3.a = 0;
4
Array of Objects

• 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.

• Thus, an array of a class type is also known as an array of objects.

• An array of objects is declared in the same way as an array of any built-in data type.

class_name array_name [size] ;


Array of Objects
class books void books :: putdata () {
{ cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n”;
char title [30];
const int size=3 ;
float price ; }
public: int main( )
{
void getdata (); books book[size] ;
void putdata (); for(int i=0;i<size;i++)
}; {
cout<<"Enter details of book "<<(i+1)<<"\n";
void books :: getdata () { book[i].getdata();
cout<<"Title:”; }
for(int i=0;i<size;i++) {
cin>>title;
cout<<"\nBook "<<(i+l)<<"\n";
cout<<"Price:”; book[i].putdata() ;
cin>>price; }
return 0;
}
}
Initialize the Array of objects with Parameterized
constructors

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

*pvalue = 25.65; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

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.

Prior to the use of object created, proper initialization is vital.

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.

E. Balaguruswamy, “Object Oriented Programming C++”, McGraw Hill


Education.
Thank You

18

You might also like