0% found this document useful (0 votes)
2 views

unit2 part4

The document explains the use of objects as function arguments in C++, detailing two methods: pass-by-value and pass-by-reference. It also covers concepts such as friend functions, constructors, and destructors, including examples of default and parameterized constructors, copy constructors, and the importance of destructors for memory management. Additionally, it highlights constructor overloading and the use of default arguments in constructors.

Uploaded by

smp540464
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit2 part4

The document explains the use of objects as function arguments in C++, detailing two methods: pass-by-value and pass-by-reference. It also covers concepts such as friend functions, constructors, and destructors, including examples of default and parameterized constructors, copy constructors, and the importance of destructors for memory management. Additionally, it highlights constructor overloading and the use of default arguments in constructors.

Uploaded by

smp540464
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

OBJECTS AS FUNCTION ARGUMENTS

Like any other data type, an object may be used as a function argument.

This can done in two ways

1. A copy of the entire object is passed to the function.

2. Only the address of the object is transferred to the function

The first method is called pass-by-value. Since a copy of the object is passed to the function,
any change made to the object inside the function do not effect the object used to call the
function. The second method is called pass-by-reference . When an address of the object is
passed, the called function works directly on the actual object used in the call. This means
that any changes made to the object inside the functions will reflect in the actual object .The
pass by reference method is more efficient since it requires to pass only the address of the
object and not the entire object.

#include <iostream>

using namespace std;

class Demo {

private:

int a;

public:

void set(int x) { a = x; }

void sum(Demo ob1, Demo ob2)

{ a = ob1.a + ob2.a; }

void print() { cout << "Value of A : " << a << endl; }

};

int main() {

// object declarations

Demo d1;
Demo d2;

Demo d3;

// assigning values to the data member of objects

d1.set(10);

d2.set(20);

// passing object d1 and d2

d3.sum(d1, d2);

// printing the values

d1.print();

d2.print();

d3.print();

return 0;

Output
Value of A : 10
Value of A : 20
Value of A : 30

Explanation
Above example demonstrate the use of object as a parameter. We
are passing d1 and d2 objects as arguments to the sum member
function and adding the value of data members a of both objects
and assigning to the current object’s (that will call the function,
which is d3) data member a.

#include <iostream>

using namespace std;

class time

int hours;
int minutes;

public:

void gettime(int h, int m)

hours = h;

minutes = m;

void puttime(void)

cout << hours << " hours and ";

cout << minutes << " minutes ";

void sum(time, time); //declaration with objects as arguments

};

void time::sum(time t1, time t2)

minutes = t1.minutes + t2.minutes;

hours = minutes / 60;

minutes = minutes % 60;

hours = hours + t1.hours + t2.hours;

int main()

time t1, t2, t3;

t1.gettime(2, 45);

t2.gettime(3, 30);

t3.sum(t1, t2);
cout << "T1= "; t1.puttime();

cout << "T2= "; t2.puttime();

cout << "T3 = "; t3.puttime();

return 0;

o/p

T1 = 2 hours and 45 minutes

T2 = 3 hours and 30 minutes

T3 = 6 hours and 15 minutes

Since the member function sum() is invoked by the objects T3, with the objects T1 and T2 as
arguments.

Friend Functions

The friend function in C++ is defined outside the scope of the class. It has the authority to
access all protected and private class members. Friends are not member functions, but the
prototypes for friend functions appear in the class function only.

A friend function processes certain special characteristics:

a. It is not in the scope of the class to which it has been declared as friend.

b. Since it is not in the scope of the class, it cannot be called using the object of that class.

c. It can be invoked like a member function without the help of any object.

d. Unlike member functions, it cannot use the member names directly.

e. It can be declared in public or private part without affecting its meaning.

f. Usually, it has objects as arguments.


#include <iostream>

using namespace std;

class sample

{ int a; int b;

public:

void setvalue()

a=25;

b=40;

friend float mean(sample s);

};

float mean(sample s)

return (float(s.a+s.b)/2.0);

int main()

sample x;

x . setvalue();

cout<<"mean value="<<mean(x)<<endl;

return(0);

o/p

mean value = 32.5


The friend function accesses the class variables a and b by using the dot operator and the
object passed to it. The function call mean(x) passes the object x by value to the friend
function.

A function friendly to two classes EXAMPLE


#include <iostream>

using namespace std;

class ABC; // forward declaration

class XYZ

int x;

public:

void setvalue(int i)

x = i;

friend void max (XYZ,ABC);

};

class ABC

int a;

public:

void setvalue( int i)

a=i;

}
friend void max(XYZ,ABC);

};

void max( XYZ m, ABC n)

if(m.x >= n.a)

cout<<m.x;

else cout<< n.a;

int main()

ABC j;

j.setvalue( 10);

XYZ s;

s.setvalue(20);

max(s,j);

return(0);

O/P

20

program on SWAPPING PRIVATE DATA OF CLASSES: how to use a


common friend function to exchange the private values of two classes.
The function is called by reference
#include <iostream>

using namespace std;


class class_2;

class class_1

int value1;

public:

void indata(int a)

value1=a;

void display(void)

cout<<value1<<endl;

friend void exchange(class_1 &, class_2 &);

};

class class_2

int value2;

public:

void indata(int a)

value2=a;

void display(void)

cout<<value2<<endl;

}
friend void exchange(class_1 &, class_2 &);

};

void exchange(class_1 &x, class_2 &y)

int temp=x.value1;

x.value1=y.value2;

y.value2=temp;

int main()

class_1 c1;

class_2 c2;

c1.indata(100);

c2.indata(200);

cout<< "values before exchange:"<<endl;

c1.display();

c2.display();

exchange(c1,c2);

cout<<"values after exchange :"<< endl;

c1.display();

c2.display();

return(0);

o/p
values before exchange

100

200
Values after exchange

200

100

In the above program the objects x and y are aliases of c1 and c2 respectively.

Constructors
A constructor is a special member function whose task is to initialize the objects of its
class . It is special because its name is the same as the class name and can be declared in the
public section . The constructor is invoked whenever an object of its associated class is
created. They do not have a return type, not even void. It is called constructor because it
construct the values of data members of the class.

Characteristics of Constructors in C++

 A constructor should be declared in the public section of the class.


 They are automatically invoked whenever the object is created.
 They don't have return types, not even void and therefore they cannot return values
 It can have default arguments.
 Constructor can't be virtual.
 They cannot be inherited , though a derived class can call the base class constructor

A constructor is declared and defined as follows:

//'class with a constructor

class integer

int m,n;

public: integer (void);//constructor declared

------------

------------

};

integer :: integer(void)

m=0; n=0;
}

When a class contains a constructor like the one defined above it is guaranteed that an object
created by the class will be initialized automatically.

For example:-

integer int1; //object int 1 created

This declaration not only creates the object int1 of type integer but also initializes its data
members m and n to zero.

A constructor that accept no parameter is called the default constructor.

The default constructor for class A is A :: A( ). If no such constructor is defined, then the
compiler supplies a default constructor .

Therefore a statement such as :-

A a ;//invokes the default constructor of the compiler of the compiler to create the object
"a" ;

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at the
time of creating object.

Let's see the simple example of C++ default Constructor.

#include <iostream>

using namespace std;

class Employee

public:

Employee()

cout<<"Default Constructor Invoked"<<endl;


}

};

int main(void)

Employee e1; //creating an object of Employee

Employee e2;

return 0;

o/p

Default Constructor Invoked

Default Constructor Invoked

Example2

#include <iostream>
using namespace std;
class abc
{ private:
char nm[];
public: abc ()
{
cout<<"enter your name:";
cin>>nm;
}
void display( )
{
cout<<nm;
}
};
int main()
{
abc d;
d.display();
getch();
return(0);
}

PARAMETERIZED CONSTRUCTOR:-
the constructors that can take arguments are called parameterized constructors.
Using parameterized constructor we can initialize the various data elements of
different objects with different values when they are created.
Example:-
class integer
{
int m,n;
public: integer( int x, int y);
--------
---------
};

integer:: integer (int x, int y)


{
m=x;
n=y;
}

The argument can be passed to the constructor by calling the constructor

implicitly or explicitly

integer int 1 = integer(0,100); // explicit call

integer int 1(0,100); //implicit call

parametrized constructor program example

#include <iostream>

using namespace std;

class integer

int m,n;

public: integer(int,int);
void display(void)

cout<<"m=:"<<m ;

cout<<"n="<<n;

};

integer :: integer( int x,int y) // constructor defined

m=x;

n=y;

int main()

integer int1(0,100); // implicit call

integer int2=integer(25,75); // explicit call

cout<<" \nobjectl "<<endl;

int1.display();

cout<<"\n object2 "<<endl;

int2.display();

output:

object 1

m=0
n=100

object2

m=25

n=25

Constructor Overloading

Constructor overloading in C++ is a technique that refers to defining multiple


constructors in a class, each with a different parameter list. This feature
provides flexibility in object initialization based on the arguments provided.

// C++ program to demonstrate example of Constructor Overloading

#include <iostream>

using namespace std;

class Demo {

private:

int X;

int Y;

public:

//Declaration of default constructor to initialize data members.

Demo();

Demo(int a, int b);

void Display();
}; //End of class

//Definition of default constructor.

Demo::Demo()

X = 10;

Y = 20;

//Definition of parameterized constructor

Demo::Demo(int a, int b)

X = a;

Y = b;

//Definition of Display() member function.

void Demo::Display()

cout << endl << "X: " << X;

cout << endl << "Y: " << Y << endl;

int main()
{

Demo d1;

cout << "Default Constructor: " << endl;

cout << "Value after initialization : ";

d1.Display();

//Constructor automatically call when object is created.

Demo d2(30, 40);

cout << "Parameterized Constructor: " << endl;

cout << "Value after initialization : ";

d2.Display();

return 0;

Output
Default Constructor:
Value after initialization:
X: 10
Y: 20
Parameterized Constructor:
Value after initialization:
X: 30
Y: 40

Note : A constructor with no parameters is known as a default constructor


Copy constructor

A copy constructor is used to declare and initialize an object from another


object. For example

integer I2(I1);

Would define the object I2 and at the same time initialize it to the values of I1.
Another form of this statement is

integer I2 =I1;

The process of initialization through a copy constructor is known as copy


initialization
// program of the copy constructor.

#include <iostream>

using namespace std;

class A

public:

int x;

A(int a) // parameterized constructor.

x=a;

A(A &i) // copy constructor

x = i.x;

};

int main()
{

A a1(20); // Calling the parameterized constructor.

A a2(a1); // Calling the copy constructor.

// A a2 = a1;

cout<<a2.x;

return 0;

o/p

20
In the above case, copy constructor can be called in the following
ways:

Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the


same class type. For example, Student s1 = s2, where Student is
the class.
o When the object of the same class type is passed by value as an
argument.
o When the function returns the object of the same class type by
value.

Constructors with default arguments

#include <iostream>

using namespace std;

class Time

{
public :

int Hours;

int Minutes;

int Seconds;

void ShowTime()

cout << "Time is "<< Hours << " Hours : "<< Minutes << " Minutes : and
" << Seconds << " Seconds \n";

Time(int TempHours, int TempMinutes=0, int TempSeconds=0)

/* see the use of default arguments in both arguments towards the end*/

Hours = TempHours;

Minutes = TempMinutes;

Seconds = TempSeconds;

};

int main()

Time Time1(12,15,15);

cout << "The Time Number 1 \n";

Time1.ShowTime();

Time Time2(10,30);

cout << "The Time Number 2 \n";


Time2.ShowTime();

return 0;

o/p

The time number 1

Time is 12 hours : 15 minutes : and 15 seconds

The time number 2

Time is 10 hours : 30 minutes : and 0 seconds

Note: the actual parameter when specified overridesthe default value. The
missing arguments must be the trailing ones

DESTRUCTOR:-

A destructor, us the name implies is used to destroy the objects that have been
created by a constructor. Like a constructor, the destructor is a member function
whose name is the same as the class name but is preceded by a tilde.

For Example :-

~ integer( ) { }

A destructor never takes any argument nor does it return any value. It will be
invoked implicitly by the compiler upon exit from the program to clean up
storage that is no longer accessible. It is a good practice to declare destructor in
a program since it releases memory space for future use.

#include <iostream>

using namespace std;

int count=0;

class alpha
{

public:

alpha()

count ++;

cout<<"\n no of object created :" <<count;

~alpha()

cout<<"\n no of object destroyed :" <<count;

count--;

};

int main()

cout<<" \n \n enter main \n:";

alpha A1,A2,A3,A4;

cout<<" \n enter block 1 :\n";

alpha A5;

{
cout<<"\n \n enter block2 \n";

alpha A6;

cout<<"\n re-enter main :\n";

return(0);

output:-

enter main

no of object created 1

no of object created 2

no of object created 3

no of object created 4

enter block 1

no of object created 5

no of object destroyed 5

enter block 2

no of object created 5

no of object destroyed 5

re-enter main

no of object destroyed 4

no of object created 3

no of object created 2

no of object created 1
NOTE: Constructors are called in order of object declaration, and
the destructors are called in the reverse order of its declaration.
Example2 Program on Destructor

#include <iostream>

using namespace std;

class Demo {

private:

int X;

public:

// constructor

Demo(int x)

X = x;

Print();

// destructor

~Demo()

cout << "\nDestructor Called";

Print();
}

void Print()

{ cout << "\nValue of X: " << X; }

};

int main()

Demo OB1(10);

Demo OB2(20);

Demo OB3(30);

return 0;

Output
Value of X: 10
Value of X: 20
Value of X: 30
Destructor Called
Value of X: 30
Destructor Called
Value of X: 20
Destructor Called
Value of X: 10

NOTE: Constructors are called in order of object declaration, and


the destructors are called in the reverse order of its declaration.

You might also like