0% found this document useful (0 votes)
1 views6 pages

Unit II

The document discusses key concepts of C++ programming, focusing on function overloading, friend functions, and pointers to class members. It explains how function overloading allows multiple functions with the same name but different parameters, and how friend functions can access private data of classes. Additionally, it covers constructors, their role in initializing class objects, and provides examples to illustrate these concepts.

Uploaded by

shashankgujrati1
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)
1 views6 pages

Unit II

The document discusses key concepts of C++ programming, focusing on function overloading, friend functions, and pointers to class members. It explains how function overloading allows multiple functions with the same name but different parameters, and how friend functions can access private data of classes. Additionally, it covers constructors, their role in initializing class objects, and provides examples to illustrate these concepts.

Uploaded by

shashankgujrati1
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/ 6

PROGRAM

UNIT II
#include<iostream.h>
int volume(double,int);
FUNCTION OVERLOADING: double volume( double , int );
double volume(longint ,int ,int);
Overloading refers to the use of the same thing for different purposes . C++ also permits overloading main( )
functions .This means that we can use the same function name to creates functions that perform a {
variety of different tasks. This is known as function polymorphism in oops. cout<<volume(10)<<endl;
Using the concepts of function overloading , a family of functions with one function name but with cout<<volume(10)<<endl; cout<<volume(10)<<endl;
different argument lists in the functions call .The correct function to be invoked is determined by }
checking the number and type of the arguments but not on the function type. int volume( ini s)
For example an overloaded add() function handles different types of data as shown {
below. return (s*s*s); //cube
//Declaration }
int add(int a, int b); //prototype 1 double volume( double r, int h)
int add (int a, int b, int c); //prototype 2 {
double add(double x, double y); //prototype 3 return(3.1416*r*r*h); //cylinder
double add(double p , double q); //prototype4 }
long volume (longint 1, int b, int h)
{
//function call return(1*b*h); //cylinder
cout<<add(5,10); //uses prototype 1 }
cout<<add(15,10.0); //uses prototype 4
cout<<add(12.5,7.5); //uses prototype 3 output:- 1000
cout<<add(5,10,15); //uses prototype 2 157.2595
cout<<add(0.75,5); //uses prototype 5 112500
A function call first matches the prototype having the same no and type of arguments and then calls
the appropriate function for execution. FRIEND FUNCTIONS:-
The function selection invokes the following steps:- 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
a) The compiler first tries to find an exact match in which the types of actual classes manager and scientist, have been defined we should like to use a function income- tax to
arguments are the same and use that function. operate on the objects of both theseclasses.
b) If an exact match is not found the compiler uses the integral promotions to the actual In such situations, c++ allows the common function lo be made friendly with both the classes , there
arguments such as: by following the function to have access to the private data of these classes .Such a function need not
char to int be a member of any of these classes.
float to double To make an outside function "friendly" to a class, we have to simply declare this function as a friend
to find amatch of the classes as shown below :
c) When either of them tails ,the compiler tries to use the built in conversions to the actual
arguments and them uses the function whose match is unique . If the conversion is possible to have class ABC
multiple matches, then the compiler will give errormessage. {
Example: ---------
long square (long n); ---------
double square(double x); public:
A function call suchas:- square(lO) --------
----------
Will cause an error because int argument can be converted to either long or friend void xyz(void);
double .There by creating an ambiguous situation as to which version of square( )should be used. };

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

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

known as friend functions. A function can be declared as a friend in any no of classes. A friend A function friendly to two classes
function, as though not a member function , has full access rights to the private members of the class. #include<iostream.h>
class abc;
A friend function processes certain special characteristics: class xyz
a. It is not in the scope of the class to which it has been declared asfriend. {
b. Since it is not in the scope of the class, it cannot be called using the object of that int x;
class. It can be invoked like a member function without the help of anyobject. public:
c. Unlike memberfunctions. void setvalue(int x) { x-= I; }
friend void max (xyz,abc);
Example: };
class abc
#include<iostream.h> {
class sample int a;
{ public:
int a; void setvalue( int i) {a=i; }
int b; friend void max(xyz,abc);
public: };
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
} void max( xyz m, abc n)
float mean (samples) {
{ if(m . x >= n.a)
return (float(s.a+s.b)/2.0); cout<<m.x;
} else
int main ( ) cout<< n.a;
{ }

sample x;
int main( )
x . setvalue( );
{
cout<<”mean value=”<<mean(x)<<endl;
abc j;
return(0);
j . setvalue( 10);
xyz s;
} s.setvalue(20);
max( s , j );
output: return(0);
mean value : 32.5 }

SWAPPING PRIVATE DATA OF CLASSES:

#include<iostream.h>

class class-2;
class class-1
{

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
int value 1; PROGRAM FOR ILLUSTRATING THE USE OF FRIEND FUNCTION:
public:
void indata( int a) { value=a; } #include< iostream.h>
void display(void) { cout<<value<<endl; } classaccount1;
friend void exchange ( class-1 &, class-2 &); classaccount2
};
{
private:
class class-2 int balance;
{
public:
int value2;
account2( ) { balance=567; }
public: void showacc2( )
void indata( int a) { value2=a; }
{
void display(void) { cout<<value2<<endl; }
cout<<”balanceinaccount2 is:”<<balance<<endl;
friend void exchange(class-l & , class-2 &);
friend int transfer (account2 &acc2, account1 &acc1,int amount);
};
};
void exchange ( class-1 &x, class-2 &y)
class acount1
{
{
int temp=x. value 1;
private:
x. value I=y.valuo2;
int balance;
y.value2=temp; public:
} account1 ( ) { balance=345; }

int main( )
{ void showacc1 ( )
class-1 c1; {
class-2 c2; cout<<”balance in account1 :”<<balance<<endl;
c1.indata(l00); }
c2.indata(200); friend int transfer (account2 &acc2, account1 &acc1 ,int amount);
cout<<”values before exchange:”<<endl; };
c1.display( );
c2.display( ); int transfer ( account2 &acc2, account1 & acc1, int amount)
exchange (c1,c2); {
cout<<”values after exchange :”<< endl; if(amount <=accl . bvalance)
c1. display ( ); {
c2. display ( ); acc2. balance + = amount;
return(0); acc1 .balance - = amount;
output: } }
else
values before exchange return(0);
100 }
200 int main()
values after exchange {
200 account1 aa;
100 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;
By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

cout<< “ balance in the accounts after the transfer:”;


aa . showacc 1 ( );
bb. showacc 2( ); RETURNING OBJECTS:
return(0); # include< iostream,h>
} class complex
output: {
balance in the accounts before transfer float x;
balance in account 1 is 345 float y;
balance in account2 is 567 public:
and transferred from account! to account2 is 100 void input( float real , float imag)
balance in account 1 is245 {
balance in account2 is667 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;
}

intmain( )
{
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

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
POINTER TO MEMBERS; DEREFERENCING OPERATOR:
It is possible to take the address of a member of a class and assign it to a pointer. The address #include<iostream.h>
of a member can be obtained by applying the operator & to a “fully qualified” class member name. class M
{
A class member pointer can be declared using the operator :: * with the class name. int x;
For Example: int y;
classA public:
{ void set_xy(int a,int b)
private: {
int m; x=a;
public: y=b;
void show( ); }
}; friend int sum(M);
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 int sum (M m)
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” int M :: * px= &M :: x; //pointer to member x

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.
int M :: * py- & m ::y;//pointer to y
The pointer ip can now be used toaccessthe m inside the member function (or M * pm=&m;
friendfunction). int s=m.* px + pm->py;
} return(s);
Let us assume that “a” is an object of “ A” declared in a member function . We can int main ( )
access "m" using the pointer ip as follows. {
cout<< a . * ip; M m;
cout<< a.m; void(M::*pf)(int,int)=&M::set-xy;//pointer to function set-xy (n*pf)( 10,20);
ap=&a; //invokes set-xy
cout<< ap-> * ip; cout<<”sum=:”<<sum(n)<<cncil;
cout<<ap->a; n *op=&n; //point to object n
The deferencing operator ->* is used as to accept a member when we use pointers to ( op->* pf)(30,40); // invokes set-xy
both the object and the member. The dereferencing operator. .* is used when the object itself is used cout<<”sum=”<<sum(n)<<end 1 ;
with the member pointer. Note that * ip is used like a member name. return(0);
We can also design pointers to member functions which ,then can be invoked using output: }
the deferencing operator in the main as shownbelow.
(object-name.* pointer-to-member function) sum= 30
(pointer-to -object -> * pointer-to-memberfunction) sum=70
The precedence of ( ) is higher than that of .* and ->* , so the parenthesis are
necessary.

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

the base class constructor .


CONSTRUCTOR:  Like other C++ function , they can have defaultarguments,
A constructor is a special member function whose task is to initialize the objects of its class .  Constructor can't bevirtual.
It is special because its name is the same as the class name. The constructor is invoked when ever an  An object with a constructor can't be used as a member of
object of its associated class is created. It is called constructor because it construct the values of data union.
members of theclass.
Example of default constructor:
A constructor is declared and defined as follows:
//'class with a constructor #include<iostream.h>
class integer #include<conio.h>
{
int m,n: class abc
public: {
integer! void);//constructor declared private:
------------ char nm[];
------------ public:
}; abc ( )
integer :: integer(void) {
{ cout<<”enter your name:”;
m=0; cin>>nm;
n=0; }
} void display( )

{
cout<<nm;
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 int main( )
This declaration not only creates the object int1 of type integerbutalso initializes its {
data members m and n tozero. clrscr( );
abc d;
A constructor that accept no parameter is called the default d.display();
constructor. The default constructor for class A is A :: A( ). If no such constructor is getch( );
defined, then the compiler supplies a default constructor. return(0);
Therefore a statement such as :- }
A a ;//invokes the default constructor of thecompilerof the
compiler to create the object "a"; 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.
Invokes the default constructor of the compiler to create the object a. Example:-
The constructor functions have some characteristics:- class integer
 They should be declared in the public section. {
 They are invoked automatically when the objects arecreated. int m,n;
 They don't have return types, not even void and therefore public:
they cannot returnvalues. integer( int x, int y);
 They cannot be inherited , though a derived class cancall --------
---------
};

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC) By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)
integer:: integer (int x, int y) Example:-
{ #include<iostream.h>
m=x;n=y; #include<conio.h>
} class abc
the argument can be passed to the constructor by calling the constructor {
implicitly. private:
integer int 1 = integer(0,100); // explicit call char nm [30];
integerint1(0,100); //implicitecall int age;
public:
abc ( ){ }// default
CLASS WITH CONSTRUCTOR:- abc ( char x[], int y);
void get( )
{
#include<iostream.h> cout<<”enter your name:”;
class integer cin>>nm;
{ cout<<” enter your age:”;
int m,n; cin>>age;
public: }
integer(int,int); void display( )
void display(void) {
cout<<nm«endl;
cout«age;
}
};
{ abc : : abc(char x[], int y)
cout<<”m=:”<<m ; {
cout<<”n=”<<n; strcpy(nm,x);
} age=y;
}; }
integer :: integer( int x,int y) // constructor defined void main( )
{ {
m=x; abc 1;
n=y; abc m=abc("computer",20000);
} l.get();
int main( ) l.dispalay( );
{ m.d isplay ();
integer int1(0,100); // implicit call getch( );
integerint2=integer(25,75); }
cout<<” \nobjectl“<<endl;
int1.display();
cout<<” \n object2 “<<endl; OVERLOADED CONSTRUCTOR:-
int2.display(); #include<iostream.h>
output: } #include<conio.h>
object 1 class sum
m=0 {
n=100 private;
object2 int a;
m=25 int b;
n=25 int c;
float d;
double e;
public:
sum ( )

By: Sweety Singhal & Priyanka Mitra (Dept. of CSE, JECRC)

{
cout<<”enter a;”; public
cin>>a; code ( ) { } //constructor
cout<<”enter b;”; code (int a) { id=a; } //constructor
cin>>b; code(code &x)
cout<<”sum= “<<a+b<<endl; {
} Id=x.id;
sum(int a,int b); }
sum(int a, float d,double c); void display( )
}; {
sum :: sum(int x,int y) cout<<id;
{ }
a=x; };
b=y; int main( )
} {
sum :: sum(int p, float q ,double r) code A(100);
{ code B(A);
a=p; code C=A;
d=q; code D;
e=r; D=A;
} cout<<” \n id of A :”; A.display( );
void main( ) cout<<” \nid of B :”; B.display( );
{ cout<<” \n id of C:”; C.display( );
clrscr( ); cout<<” \n id of D:”; D.display( );
sum 1; }
sum m=sum(20,50);
sum n= sum(3,3.2,4.55);
getch(); output :-
} id of A:100
id of B:100
output: id of C:100
enter a : 3 id ofD:100
enter b : 8
sum=11
sum=70 DYNAMIC CONSTRUCTOR:-
sum=10.75 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.
COPY CONSTRUCTOR: Allocate of memory to objects at the time of their construction is known as dynamic
A copy constructor is used to declare and initialize an object from another object. constructors of objects. The memory is allocated with the help of new operator.
Example:- Example:-
the statement #include<iostream.h>
integer 12(11); #include<string.h>
would define the object 12 and at the same time initialize it to the values of 11. class string
Another form of this statement is : integer 12=11; {
The process of initialization through a copy constructor is known as copy initialization. char *name;
Example:-
#incliide<iostream.h>
class code
{
int id; int length;
public:
string ()
{
length=0; DESTRUCTOR:-
name= new char [length+1]; /* one extra for \0 */
} A destructor, us the name implies is used to destroy the objects that have been created by a
string( char *s) //constructor 2 constructor. Like a constructor, the destructor is a member function whose name is the same as the
{ class name but is preceded by atilde.
length=strlen(s);
name=new char[length+1]; For Example:-
strcpy(name,s);
~ integer( ) { }
} A destructor never takes any argument nor does it return any value. It will be invoked
void display(void) 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
cout<<name<<endl; future use.
}
Delete is used to free memory which is created by new.
void join(string &a .string &b)
Example:-
{
matrix : : ~ matrix( )
length=a. length +b . length;
{
delete name;
for(int i=0; i<11;i++)
name=new char[length+l]; /* dynamic allocation */
delete p[i];
strcpy(name,a.name); delete p;
strcat(name,b.name); }
}
};
int main()
{ IMPLEMENTATAION OF DESTRUCTORS:-
char * first = “Joseph” ; #include<iostream.h>
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2; int count=0;
sl.join(name1,name2); class alpha
s2.join(s1,name3); {
namel.display( ); public:
name2.display( ); alpha( )
name3.display( ); {
s1.display(); count ++;
s2.display(); cout<<”\n no of object created :”<<endl;
} }
output :- ~alpha( )
Joseph {
Louis cout<<”\n no of object destroyed :” <<endl;
language coutnt--;
Joseph Louis }
Joseph Louis Language };

int main()
{

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


alpha A1,A2,A3,A4;
{
cout<<” \n enter block 1 :\n”;

alpha A5; New & Delete Operators


}
{
cout<<” \n \n enter block2 \n”; Dynamic memory allocation means creating memory at runtime. For example, when we declare an
alphaA6; array, we must provide size of array in our source code to allocate memory at compile time.
}
cout<<\n re-enter main \n:”; But if we need to allocate memory at runtime me must use new operator followed by data type. If
we need to allocate memory for more than one element, we must provide total number of elements
return(0);
} required in square bracket[ ]. It will return the address of first byte of memory.

output:- Syntax of new operator


enter main
no of object created 1
no of object created 2 ptr = new data-type;
no of object created 3
no of object created 4 //allocte memory for one element
enter block1
no of object created 5
no of object destroyed 5 ptr = new data-type [ size ];
enter block2
//allocte memory for fixed number of element
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 created1 Delete operator is used to deallocate the memory created by new operator at run-time. Once the
memory is no longer needed it should by freed so that the memory becomes available again for
Example :- other request of dynamic memory.
#include<iostream.h>
int x=l; Syntax of delete operator
class abc
{
public:
delete ptr;
abc( )
{ //deallocte memory for one element
x--;
cout<<”construct the no”<<x<<endl;
} delete[] ptr;
~abc( )
{ //deallocte memory for array
cout<<”destruct the no:”<<x<<endl;
x--;
}
};
int main( )
{
abc I1,I2,I3,I4; Example of c++ new and delete operator
cout«ll«12«13«l4«endl;
return(0);
}

25 P.T.O
#include<iostream.h> void main()
#include<conio.h> {

int size,i;
int *ptr;

cout<<"\n\tEnter size of Array : ";


cin>>size;

ptr = new int[size];


//Creating memory at run-time and return first byte of address to ptr.
for(i=0;i<5;i++) //Input arrray fromuser.
{
cout<<"\nEnter any number : ";
cin>>ptr[i];
}
for(i=0;i<5;i++) //Output arrray toconsole.
cout<<ptr[i]<<", ";
delete[] ptr;
//deallocating all the memory created by new operator

}
Output :
Enter size of Array : 5
Enter any number : 78
Enter any number : 45
Enter any number : 12
Enter any number : 89
Enter any number : 56

78, 45, 12, 89, 56,

26 P.T.O 27 P.T.O

You might also like