Lecture Notes On: Department of Computer Science & Engineering Jaipur Engineering College & Research Centre, Jaipur
Lecture Notes On: Department of Computer Science & Engineering Jaipur Engineering College & Research Centre, Jaipur
on
3CS4-06
Unit II
/ P P P P P P P P P
Subject
O O O
Code
T CO O O O O O O O O O
1 1 1
/ 1 2 3 4 5 6 7 8 9
0 1 2
P
Understand the paradigms of
object oriented programming in 3 3 3 2 2 2 1 1 0 1 1 3
L
comparison of procedural
Object Oriented Programming
oriented programming.
Apply the class structure as
L programming.
fundamental, building block for
computational programming. 3 3 3 3 2 2 1 1 1 2 1 3
capacity in communication
3CS4-06
programming.
system.
Apply the major object-oriented
III concepts to implement object
L 3 3 3 3 2 1 2 2 1 2 1 3
oriented programs in C++.
FUNCTION OVERLOADING:
Overloading refers to the use of the same thing for different purposes . C++ also permits overloading
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.
Using the concepts of function overloading , a family of functions with one function name but with
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.
For example an overloaded add() function handles different types of data as shown
below.
//Declaration
int add(int a, int b); //prototype 1
int add (int a, int b, int c); //prototype 2
double add(double x, double y); //prototype 3
double add(double p , double q); //prototype4
//function call
cout<<add(5,10); //uses prototype 1
cout<<add(15,10.0); //uses prototype 4
cout<<add(12.5,7.5); //uses prototype 3
cout<<add(5,10,15); //uses prototype 2
cout<<add(0.75,5); //uses prototype 5
A function call first matches the prototype having the same no and type of arguments and then calls
the appropriate function for execution.
The function selection invokes the following steps:-
a) The compiler first tries to find an exact match in which the types of actual
arguments are the same and use that function.
b) If an exact match is not found the compiler uses the integral promotions to the actual
arguments such as:
char to int
float to double
to find amatch
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
multiple matches, then the compiler will give errormessage.
Example:
long square (long n);
double square(double x);
A function call suchas:- square(lO)
Will cause an error because int argument can be converted to either long or
double .There by creating an ambiguous situation as to which version of square( )should be used.
#include<iostream.h>
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int);
main( )
{
cout<<volume(10)<<endl;
cout<<volume(10)<<endl; cout<<volume(10)<<endl;
}
int volume( ini s)
{
return (s*s*s); //cube
}
double volume( double r, int h)
{
return(3.1416*r*r*h); //cylinder
}
long volume (longint 1, int b, int h)
{
return(1*b*h); //cylinder
}
output:- 1000
157.2595
112500
FRIEND 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 theseclasses.
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
Example:
#include<iostream.h>
class sample
{
int a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
}
float mean (samples)
{
return (float(s.a+s.b)/2.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
return(0);
output:
mean value : 32.5
int main( )
{
abc j;
j . setvalue( 10);
xyz s;
s.setvalue(20);
max( s , j );
return(0);
}
#include<iostream.h>
class class-2;
class class-1
{
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: }
#include< iostream.h>
classaccount1;
classaccount2
{
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);
};
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
A class member pointer can be declared using the operator :: * with the class name.
For Example:
classA
{
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 pointer ip can now be used toaccessthe m inside the member function (or
friendfunction).
int sum (M m)
{
int M :: * px= &M :: x; //pointer to member x
sum= 30
sum=70
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 integerbutalso initializes its
data members m and n tozero.
#include<iostream.h>
#include<conio.h>
class abc
{
private:
char nm[];
public:
abc ( )
{
cout<<”enter your name:”;
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:
integer( int x, int y);
--------
---------
};
#include<iostream.h>
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
integerint2=integer(25,75);
cout<<” \nobjectl“<<endl;
int1.display();
cout<<” \n object2 “<<endl;
int2.display();
output: }
object 1
m=0
n=100
object2
m=25
n=25
OVERLOADED CONSTRUCTOR:-
#include<iostream.h>
#include<conio.h>
class sum
{
private;
int a;
int b;
int c;
float d;
double e;
public:
sum ( )
{
cout<<”enter a;”;
cin>>a;
cout<<”enter b;”;
cin>>b;
cout<<”sum= “<<a+b<<endl;
}
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;
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;
cout<<” \n id of A :”; A.display( );
cout<<” \nid of B :”; B.display( );
cout<<” \n id of C:”; C.display( );
cout<<” \n id of D:”; D.display( );
}
output :-
id of A:100
id of B:100
id of C:100
id ofD: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 ()
{
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()
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2;
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
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 atilde.
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;
}
IMPLEMENTATAION OF DESTRUCTORS:-
#include<iostream.h>
int count=0;
class alpha
{
public:
alpha( )
{
count ++;
cout<<”\n no of object created :”<<endl;
}
~alpha( )
{
cout<<”\n no of object destroyed :” <<endl;
coutnt--;
}
};
int main()
{
output:-
enter main
no of object created 1
no of object created 2
no of object created 3
no of object created 4
enter block1
no of object created 5
no of object destroyed 5
enter block2
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
Example :-
#include<iostream.h>
int x=l;
class abc
{
public:
abc( )
{
x--;
cout<<”construct the no”<<x<<endl;
}
~abc( )
{
cout<<”destruct the no:”<<x<<endl;
x--;
}
};
int main( )
{
abc I1,I2,I3,I4;
cout«ll«12«13«l4«endl;
return(0);
}
New & Delete Operators
Dynamic memory allocation means creating memory at runtime. For example, when we declare an
array, we must provide size of array in our source code to allocate memory at compile time.
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
required in square bracket[ ]. It will return the address of first byte of memory.
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
other request of dynamic memory.
delete ptr;
//deallocte memory for one element
delete[] ptr;
//deallocte memory for array
25 P.T.O
#include<iostream.h>
#include<conio.h>
26 P.T.O
void main()
{
int size,i;
int *ptr;
}
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
27 P.T.O