Unit II AI - DS
Unit II AI - DS
on
3AID4-06
Unit II
CO2 Explain the memory management techniques using constructors, destructors, pointers
and friend function.
CO3 Classify and demonstrate the various Inheritance and polymorphism techniques.
L
P P P
/ P P P P P P P P P
C
Semester
O O O
Subject
T O O O O O O O O O O
Code
/
1 1 1
1 2 3 4 5 6 7 8 9
0 1 2
P
Describe the OOPs paradigm
with the concept of objects,
L classes, data member and 3 3 3 2 2 2 1 1 0 1 1 3
member function.
Object Oriented Programming
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.
PROGRAM
#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:
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.
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
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);
};
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
{
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: }
#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
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:
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
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 theclass.
};
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 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);
};
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
integerint1(0,100); //implicitecall
#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
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( )
{
cout<<”enter your name:”;
cin>>nm;
cout<<” enter your age:”;
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.d isplay ();
getch( );
}
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