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

04ConstructorAndDestructor

Uploaded by

nanigir651
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)
14 views

04ConstructorAndDestructor

Uploaded by

nanigir651
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/ 18

SHRI SHANKARACHARYA TECHNICAL CAMPUS

LECTURE-18

FRIENDLY FUNCTIONS:-
We know private members can not be accessed from outside the class. That is a non -
member function can't have an access to the private data of a class. However there could be a case
where two classes manager and scientist, have been defined we should like to use a function income-
tax to operate on the objects of both these classes.
In such situations, c++ allows the common function lo be made friendly with both the classes , there
by following the function to have access to the private data of these classes .Such a function need not
be a member of any of these classes.
To make an outside function "friendly" to a class, we have to simply declare this function as a friend
of the classes as shown below :

class ABC
{
---------
---------
public:
--------
----------
friend void xyz(void);
};

The function declaration should be preceded by the keyword friend , The function is defined else
where in the program like a normal C ++ function . The function definition does not use their the
keyword friend or the scope operator :: . The functions that are declared with the keyword friend are
known as friend functions. A function can be declared as a friend in any no of classes. A friend
function, as though not a member function , has full access rights to the private members of the class.

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. It can be invoked like a member function without the help of any object.
c. Unlike member functions.

Example:

#include<iostream.h>
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);
}

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 1


SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main ( )
{

sample x;
x . setvalue( );
cout mean value= mean(x)<<endl;
return(0);

output:
mean value : 32.5

A function friendly to two classes


#include<iostream.h>
class abc;
class xyz
{
int x;
public:
void setvalue(int x) { 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);
}

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 2


SHRI SHANKARACHARYA TECHNICAL CAMPUS
SWAPPING PRIVATE DATA OF CLASSES:

#include<iostream.h>

class class-2;
class class-1
{

int value 1;
public:
void indata( int a) { value=a; }
void display(void) { cout<<value<<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-l & , class-2 &);
};
void exchange ( class-1 &x, class-2 &y)
{
int temp=x. value 1;
x. value I=y.valuo2;
y.value2=temp;
}

int main( )
{
class-1 c1;
class-2 c2;
c1.indata(l00);
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);
}

output:
values before exchange
100
200
values after exchange
200
100
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 3
SHRI SHANKARACHARYA TECHNICAL CAMPUS

PROGRAM FOR ILLUSTRATING THE USE OF FRIEND FUNCTION:

#include< iostream.h>
class account1;
class account2 {
private:
int balance;
public:
account2( ) { balance=567; }
void showacc2( )
{
cout balanceinaccount2 is: balance<<endl;
friend int transfer (account2 &acc2, account1 &acc1,int amount);
};
class acount1 {
private:
int balance;
public:
account1 ( ) { balance=345; }

void showacc1 ( ) {
cout balance in account1 : balance<<endl; }
friend int transfer (account2 &acc2, account1 &acc1 ,int amount);
};

int transfer ( account2 &acc2, account1 & acc1, int amount) {


if(amount <=accl . bvalance) {
acc2. balance + = amount;
acc1 .balance - = amount; }
else
return(0);
}

int main()
{
account1 aa;
account2 bb;

cout << balance in the accounts before transfer: ;


aa . showacc1( );
bb . showacc2( );
cout << amt transferred from account1 to account2 is: ;
cout<<transfer ( bb,aa,100)<<endl;

cout balance in the accounts after the transfer: ;


aa . showacc 1 ( );
bb. showacc 2( );
return(0);
}

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 4


SHRI SHANKARACHARYA TECHNICAL CAMPUS
output:
balance in the accounts before transfer
balance in account 1 is 345
balance in account2 is 567
and transferred from account! to account2 is 100
balance in account 1 is 245
balance in account2 is 667

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 5


SHRI SHANKARACHARYA TECHNICAL CAMPUS
LECTURE-19

RETURNING OBJECTS:
# include< iostream,h>
class complex
{
float x;
float y;
public:
void input( float real , float imag)
{
x=real;
y=imag;
}
friend complex sum( complex , complex);
void show ( complex );
};
complex sum ( complex c1, complex c2)
{
complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return c3;}

void complex :: show ( complex c)


{
cout<<c.x +j c.y<<endl;
}

int main( )
{
complex a, b,c;
a.input(3.1,5.65);
b.input(2.75,1.2);
c=sum(a,b);
cout a= ; a.show(a);
cout b= ; b.show(b);
cout c= ; c.show(c);
return(0);
}
output:
a =3.1 + j 5.65
b= 2.75+ j 1.2
c= 5.55 + j 6.85

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 6


SHRI SHANKARACHARYA TECHNICAL CAMPUS
POINTER TO MEMBERS;
It is possible to take the address of a member of a class and assign it to a pointer. The address
of a member can be obtained by applying the operator & to a fully qualified class member name.

A class member pointer can be declared using the operator :: * with the class name.
For Example:
class A
{
private:
int m;
public:
void show( );
};
We can define a pointer to the member m as follows :
int A :: * ip = & A :: m
The ip pointer created thus acts like a class member in that it must be invoked with a class object. In
the above statement. The phrase A :: * means pointer - to - member of a class . The phrase & A ::
m means the Address of the m member of a class

The following statement is not valid :


int *ip=&m ; // invalid
This is because m is not simply an int type data. It has meaning only when it is associated
with the class to which it belongs. The scope operator must be applied to both the pointer and the
member.

The pointer ip can now be used to access the m inside the member function (or
friend function).

access "m" using the pointer ip as follows.


cout<< a . * ip;
cout<< a.m;
ap=&a;
cout<< ap-> * ip;
cout<<ap->a;
The deferencing operator ->* is used as to accept a member when we use pointers to
both the object and the member. The dereferencing operator. .* is used when the object itself is used
with the member pointer. Note that * ip is used like a member name.
We can also design pointers to member functions which ,then can be invoked using
the deferencing operator in the main as shown below.
(object-name.* pointer-to-member function)
(pointer-to -object -> * pointer-to-member function)
The precedence of ( ) is higher than that of .* and ->* , so the parenthesis are
necessary.

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 7


SHRI SHANKARACHARYA TECHNICAL CAMPUS
DEREFERENCING OPERATOR:
#include<iostream.h>
class M
{
int x;
int y;
public:
void set_xy(int a,int b)
{
x=a;
y=b;
}
friend int sum(M);
};

int sum (M m)
{
int M :: * px= &M :: x; //pointer to member x

int M :: * py- & m ::y;//pointer to y


M * pm=&m;
int s=m.* px + pm->py;
return(s);
}
int main ( )
{
M m;
void(M::*pf)(int,int)=&M::set-xy;//pointer to function set-xy (n*pf)( 10,20);
//invokes set-xy
cncil;
n *op=&n; //point to object n
( op->* pf)(30,40); // invokes set-xy

return(0);
}
output:
sum= 30
sum=70

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 8


SHRI SHANKARACHARYA TECHNICAL CAMPUS
LECTURE-20

CONSTRUCTOR:
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. The constructor is invoked when ever an
object of its associated class is created. It is called constructor because it construct the values of data
members of the class.

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" ;

Invokes the default constructor of the compiler to create the object a.


The constructor functions have some characteristics:-
They should be declared in the public section .
They are invoked automatically when the objects are created.
They don't have return types, not even void and therefore
they cannot return values.
They cannot be inherited , though a derived class can call

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 9


SHRI SHANKARACHARYA TECHNICAL CAMPUS
the base class constructor .
Like other C++ function , they can have default arguments,
Constructor can't be virtual.
An object with a constructor can't be used as a member of
union.

Example of default constructor:

#include<iostream.h>
#include<conio.h>

class abc
{
private:
char nm[];
public:
abc ( )
{

cin>>nm;
}
void display( )

{
cout<<nm;
}

};

int main( )
{
clrscr( );
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:

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 10


SHRI SHANKARACHARYA TECHNICAL CAMPUS
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.
integer int 1 = integer(0,100); // explicit call
integer int 1(0,100); //implicite call

CLASS WITH CONSTRUCTOR:-

#include<iostream.h>
class integer
{
int m,n;
public:
integer(int,int);
void display(void)

};

output:
object 1 m=0 n=100 object2 m=25 n=25

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


{
m=x; n=y; }

int main( )
{
integer int 1(0, 100); // implicit call integer
int2=integer(25,75);

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 11


SHRI SHANKARACHARYA TECHNICAL CAMPUS
\ int1.display( )
;
\ int2.display( );}

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 12


SHRI SHANKARACHARYA TECHNICAL CAMPUS

Example:-
#include<iostream.h>
#include<conio.h> class
abc
{ private:
char nm [30];
int age;
public:
abc ( ){ }// default abc
( char x[], int y); void
get( )
{

cin>>nm;

cin>>age; }
void display( ) {
cout<<nm«endl;
cout«age;
}
};
abc : : abc(char x[], int y) {
strcpy(nm,x);
age=y;
}
void main( )
{
abc 1;
abc m=abc("computer",20000);
l.get();
l.dispalay( );
m.display ( );
getch( );
}

OVERLOADED CONSTRUCTOR:-
#include<iostream.h> #include<conio.h>
class sum {
private;
int a; int
b; int c;
float d;
double e;
public:
sum ( ){

cin>>a;
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 13
SHRI SHANKARACHARYA TECHNICAL CAMPUS
cin>>b;

}
sum(int a,int b);
sum(int a, float d,double c);
};
sum :: sum(int x,int y)
{
a=x;
b=y;
}
sum :: sum(int p, float q ,double r)
{
a=p;
d=q;
e=r;
}
void main( )
{
clrscr( );
sum 1;
sum m=sum(20,50);
sum n= sum(3,3.2,4.55);
getch( );
}

output:
enter a : 3
enter b : 8
sum=11
sum=70
sum=10.75

COPY CONSTRUCTOR:
A copy constructor is used to declare and initialize an object from another object.
Example:-
the statement
integer 12(11);
would define the object 12 and at the same time initialize it to the values of 11.
Another form of this statement is : integer 12=11;
The process of initialization through a copy constructor is known as copy initialization.
Example:-
#incliide<iostream.h>
class code
{
int id;

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 14


SHRI SHANKARACHARYA TECHNICAL CAMPUS

public
code ( ) { } //constructor
code (int a) { id=a; } //constructor code(code &x)
{
Id=x.id; }
void display( ) {
cout<<id; }
};

int main( ) {
code A(100); code B(A); code C=A; code D; D=A;
\\\\ );
}

output :-
id of A:100
id of B:100
id of C:100
id of D:100

DYNAMIC CONSTRUCTOR:-
The constructors can also be used to allocate memory while creating objects .
This will enable the system to allocate the right amount of memory for each object when the objects
are not of the same size, thus resulting in the saving of memory.
Allocate of memory to objects at the time of their construction is known as dynamic
constructors of objects. The memory is allocated with the help of new operator.
Example:-
#include<iostream.h>
#include<string.h>
class string
{
char *name;

int length;
public:
string ( )

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 15


SHRI SHANKARACHARYA TECHNICAL CAMPUS
{
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<endl;
}
void join(string &a .string &b)
{
length=a. length +b . length;
delete name;
name=new char[length+l]; /* dynamic allocation */
strcpy(name,a.name);
strcat(name,b.name);
}
};
int main( )
{

sl.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
}
output :-
Joseph
Louis
language
Joseph Louis
Joseph Louis Language

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 16


SHRI SHANKARACHARYA TECHNICAL CAMPUS
LECTURE-21

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.
Delete is used to free memory which is created by new.
Example:-
matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}

IMPLEMENTED OF DESTRUCTORS:-
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha( )
{
count ++;
\
}
~alpha( )
{
\
coutnt--;
}
};

int main( )
{

\n \n enter main \
alpha A1,A2,A3,A4;
{
\n enter block 1 :\
SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 17
SHRI SHANKARACHARYA TECHNICAL CAMPUS
alpha A5; }
{
\n \n enter block2 \
alpha A6;
}
cout<<\n re-enter main \
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

Example :-
#include<iostream.h>
int x=l;
class abc {
public:
abc( ) {
x--;

}
~abc( ) {
co
x--;
}

};
int main( ) {
abc I1,I2,I3,I4;
cout«ll«12«13«l4«endl;
return(0);
}

SOMESH KUMAR DEWANGAN DEPARTMENT OF CSE 18

You might also like