oops
EXPT. NO. 1 WRITE A PROGRAM TO DISPLAY INFORMATION OF
STUDENT
OBJECTS
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program
must handle.
The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real
word entity. For example: consider an example named Amit; Amit is 25 years old and
his salary is 2500.
The Amit may be represented in a computer program as an object. The data part of the
object would be (name: Amit, age: 25, salary: 2500).
Class : Class is a group of objects that share common properties and relationships .In
C++,data type that contains member variables and member functions that operates on
the variables.
2
A class is defined with the keyword class. It allows the data to be hidden, if necessary
from external use. When we defining a class, we are creating a new abstract data type
that can be treated like any other built in data type.
Generally a class specification has two parts:-
a) Class declaration
b) Class function definition
the class declaration describes the type and scope of its members. The class function
definition describes how the class functions are implemented.
Syntax:-
class class-name
{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};
The members that have been declared as private can be accessed only from with in the
class. On the other hand , public members can be accessed from outside the class
also.
The data hiding is the key feature of oops. The use of keywords private is optional by
default, the members of a class are private.
The variables declared inside the class are known as data members and the functions
are known as members mid the functions. Only the member functions can have access
to the private data members and private functions.
However, the public members can be accessed from the outside the class. The binding
of data and functions together into a single class type variable is referred to as
encapsulation.
# include<iostream.h>
class student
{
char name[30];
int age;
public:
void getdata( );
void display( );
};
void student :: getdata ( )
{
cout<<”enter name”;
cin>>name;
cout<<”enter age”;
cin>>age;
}
3
void student :: display()
{
cout<<”\n name:”<<name;
cout<<”\n age:”<<age;
}
void main( )
{ student p;
p.getdata();
p.display();
}
Output:
4
EXPT. NO. 2 WRITE A PROGRAM TO STUDY THE OPERATION OF
INLINE FUNCTION
To eliminate the cost of calls to small functions C++ proposes a new feature called
inline function. An inline function is a function that is expanded inline when it is
invoked .That is the compiler replaces the function call with the corresponding function
code.
The inline functions are defined as follows:-
inline function-header
{f
unction body;
}
Example: inline double cube (double a)
{ return(a*a*a);
}
The above inline function can be invoked by statements like
c=cube(3.0);
d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the
compliler. The compiler may ignore this request if the function definition is too long or
too complicated and compile the function as a normal function.
#include<iostream.h>
#include<stdio.h>
inline float mul(float x, float y)
{ return(x*y);
}i
nline double div(double p.double q)
{ return(p/q);
}
void main( )
{f
loat a=12.345;
float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
}
Output
5
EXPT. NO. 3 WRITE A PROGRAM TO IMPLEMENT 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); //prototype 4
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 a match
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 .
#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;
}i
nt volume( ini s)
{ return (
s*s*s); //cube
}
double volume( double r, int h)
{
return(3.1416*r*r*h); //cylinder
}l
ong volume (longint 1, int b, int h)
{r
eturn(1*b*h); //cylinder
}
6
EXPT. NO.4 PROGRAM FOR ILLUSTRATING THE USE OF FRIEND
FUNCTION
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 incometax 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.
#include<iostream.h>
class sample
{i
nt a;
int b;
public:
void setvalue( ) { a=25;b=40;}
friend float mean( sample s);
}f
loat mean (sample s)
{r
eturn (float(s.a+s.b)/2.0);
}
7
int main ( )
{
sample x;
x . setvalue( );
cout<<”mean value=”<<mean(x)<<endl;
return(0);
}
output
#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;
}f
riend int transfer (account2 &acc2, account1 &acc1 ,int amount);
};
int transfer ( account2 &acc2, account1 & acc1, int amount)
{i
f(amount <=accl . bvalance)
{
acc2. balance + = amount;
acc1 .balance - = amount;
}
else
return(0);
}i
nt 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);
}
output:
8
EXPT. NO.5 PROGRAM FOR ILLUSTRATING THE USE OF DEFAULT
AND PARAMETERISED CONSTRUCTUOR
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
{i
nt 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 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:
9
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
{i
nt m,n;
public:
integer( int x, int y);
--------
---------
};
integer:: integer (int x, int y)
{
m=x;n=y;
}
CLASS WITH PARAMETERIZED CONSTRUCTOR:-
#include<iostream.h>
class integer
{i
nt 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;
}i
nt main( )
10
{i
nteger int 1(0, 100); // implicit call
integer int2=integer(25,75);
cout<<” \nobjectl “<<endl;
int1.display( );
cout<<” \n object2 “<<endl;
int2.display( );
}
11
EXPT. NO.6 WRITE A PROGRAM ON CONSTRUCTUOR OVERLOADING.
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;
}s
um(int a,int b);
sum(int a, float d,double c);
};
sum :: sum(int x,int y)
{
a=x;
b=y;
}s
um :: 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:
12
EXPT. NO.7 WRITE A PROGRAM ON COPY CONSTRUCTUOR AND
DYNAMIC CONSTRUCTOR.
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:-
#include<iostream.h>
class code
{i
nt id;
public
code ( ) { } //constructor
code (int a) { id=a; } //constructor
code(code &x)
{I
d=x.id;
}
void display( )
{c
out<<id;
}}
;
int main( )
{c
ode 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 :-
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:-
13
#include<iostream.h>
#include<string.h>
class string
{
char *name;
int length;
public:
string ( )
{l
ength=0;
name= new char [length+1]; /* one extra for \0 */
}s
tring( char *s) //constructor 2
{l
ength=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<endl;
}
void join(string &a .string &b)
{l
ength=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 :-
14
EXPT. NO. 8 UNARY OPERATOR+ FOR ADDING TWO COMPLEX
NUMBERS (USING MEMBER FUNCTION)
class complex
{ float real,img;
public:
complex()
{ real=0;
img=0;
} complex(float r,float i)
{ real=r;
img=i;
}
void show()
{ cout<<real<<”+i”<<img;
} complex operator+(complex &
p)
{ complex w;
w.real=real+q.real;
w.img=img+q.img;
return w;
}}
;
void main()
{ complex s(3,4);
complex t(4,5);
complex m;
m=s+t;
s.show();
t.show();
m.show();
}
OUTPUT:
15
EXPT. NO. 9 WRITE A C++ ON STATIC DATA AND FUNCTION
STATIC DATA MEMBER:
A data member of a class can be qualified as static . The properties of a static member
variable are similar to that of a static variable. A static member variable
has contain special characteristics.
Variable has contain special characteristics:-
1) It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
2) Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
3) It is visible only with in the class but its life time is the entire program. Static
variables are normally used to maintain values common to the entire class.
For example a static data member can be used as a counter that records the
occurrence of all the objects.
int item :: count; // definition of static data member
Note that the type and scope of each static member variable must be defined outside
the class definition .This is necessary because the static data members are stored
separately rather than as a part of an object.
Example :-
#include<iostream.h>
class item
{ static int count; //count is static
int number;
public:
void getdata(int a)
.
{
number=a;
count++;
}
void getcount(void)
{
cout<<”count:”;
cout<<count<<endl;
} };
int item :: count ; //count defined
int main( )
{i
tem a,b,c;
a.get_count( );
b.get_count( );
c.get_count( ):
a.getdata( ):
b.getdata( );
c.getdata( );
cout«"after reading data : "«endl;
a.get_count( );
16
b.gel_count( );
c.get count( );
return(0);
}
STATIC MEMBER FUNCTIONS:-
A member function that is declared static has following properties :-
1. A static function can have access to only other static members declared in the
same class.
2. A static member function can be called using the class name as follows:-
class - name :: function - name;
Example:-
#include<iostream.h>
class test
{i
nt code;
static int count; // static member variable
public:
void set(void)
{
code=++count;
}
void showcode(void)
{
cout<<”object member : “<<code<<end;
} static void showcount(void)
{ cout<<”count=”<<count<<endl; }
};
int test:: count;
int main()
{t
est t1,t2;
t1.setcode( );
t2.setcode( );
test :: showcount ( ); '
test t3;
t3.setcode( );
test:: showcount( );
t1.showcode( );
t2.showcode( );
t3.showcode( );
return(0);
}
17
EXPT. NO. 10 WRITE A PROGRAM TO USE OBJECT AS
FUNCTION ARGUMENTS.
Like any other data type, an object may be used as A function argument. This can
cone 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.
Example:-
#include<iostream.h>
class time
{i
nt hours;
int minutes;
public:
void gettime(int h, int m)
{
hours=h;
minutes=m;
}
void puttime(void)
{
cout<< hours<<”hours and:”;
cout<<minutes<<”minutes:”<<end;
}
void sum( time ,time);
};
void time :: sum (time t1,time t2) .
{
minutes=t1.minutes + t2.minutes;
hours=minutes%60;
minutes=minutes%60;
hours=hours+t 1.hours+t2.hours;
}i
nt main()
{t
ime 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);
}
18
EXPT. NO. 11 WRITE A PROGRAM TO USE SINGLE
INHERITANCE AND MULTILEVEL INHERITANCE
Single Inheritance
When a class inherits from a single base class, it is known as single inheritance.
Following program
shows the single inheritance using public derivation.
#include<iostream.h>
#include<conio.h>
class worker
{int age;
char name [10];
public:
void get ( );
};
void worker : : get ( )
{
cout <<”yout name please”
cin >> name;
cout <<”your age please” ;
cin >> age;
}
void worker :: show ( )
{
cout <<”In My name is :”<<name<<”In My age is :”<<age;
}
class manager :: public worker //derived class (publicly)
{i
nt now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get ( ) ; //the calling of base class input fn.
cout << “number of workers under you”;
cin >> now;
cin>>name>>age;
}(
if they were public )
void manager :: show ( )
{
worker :: show ( ); //calling of base class o/p fn.
cout <<“in No. of workers under me are: “ << now;
}
main ( )
{
clrscr ( ) ;
worker W1;
manager M1;
M1 .get ( );
M1.show ( ) ;
}
19
Multilevel Inheritance
When the inheritance is such that, the class A serves as a base class for a derived class
B which in turn serves as a base class for the derived class C. This type of inheritance
is called ‘MULTILEVEL INHERITENCE’.
The declaration for the same would be:
Class A
{/
/body
}
Class B : public A
{/
/body
}
Class C : public B
{/
/body
}
This declaration will form the different levels of inheritance.
Following program exhibits the multilevel inheritance.
#include<iostream.h>
#include<conio.h>
class worker // Base class declaration
{i
nt age;
char name [20] ;
public;
void get( ) ;void show( ) ;
}
void worker: get ( )
{
cout << “your name please” ;
cin >> name;
cout << “your age please” ;
}
void worker : : show ( )
{
cout << “In my name is : “ <<name<< “ In my age is : “ <<age;
}
class manager : public worker //Intermediate base class derived
{
20
//publicly from the base class
int now;
public:
void get ( ) ;
void show( ) ;
};
void manager :: get ( )
{
worker : :get () ; //calling get ( ) fn. of base class
cout << “no. of workers under you:”;
cin >> now;
}
void manager : : show ( )
{
worker : : show ( ) ; //calling show ( ) fn. of base class
cout << “In no. of workers under me are: “<< now;
}
class ceo: public manager //declaration of derived class
{/
/publicly inherited from the
int nom;
//intermediate base class
public:
void get ( ) ;
void show ( ) ;
};
void ceo : : get ( )
{
manager : : get ( ) ;
cout << “no. of managers under you are:”; cin >> nom;
}
void manager : : show ( )
{
cout << “In the no. of managers under me are: In”;
cout << “nom;
}main ( )
{
clrscr ( ) ;
ceo cl ;
cl.get ( ) ; cout << “\n\n”;
cl.show ( ) ;
}
21
EXPT. NO. 11 WRITE A PROGRAM TO USE SINGLE
MULTIPLE INHERITANCES AND HIERARCHICAL
INHERITANCE
A class can inherit the attributes of two or more classes. This mechanism is known as
‘MULTIPLE INHERITENCE’. Multiple inheritance allows us to combine the
features of several existing classes as a starring point for defining new classes.
#include<iostream.h>
#include<conio . h>
class father
//Declaration of base classl
{i
nt age ;
char flame [20] ;
public:
void get ( ) ;
void show ( ) ;
};
void father : : get ( )
{
cout << “your father name please”;
cin >> name;
cout << “Enter the age”;
cin >> age;
}
void father : : show ( )
{
cout<< “In my father’s name is: ‘ <<name<< “In my father’s age is:<<age;
}
class mother
//Declaration of base class 2
{
char name [20] ;
int age ;public:
void get ( )
{
cout << “mother’s name please” << “In”;
cin >> name;
cout << “mother’s age please” << “in”;
cin >> age;
}
void show ( )
22
{
cout << “In my mother’s name is: “ <<name;
cout << “In my mother’s age is: “ <<age;
}
class daughter : public father, public mother //derived class inheriting
{/
/publicly
char name [20] ; //the features of both the base class
int std;
public:
void get ( ) ;
void show ( ) ;
};
void daughter :: get ( )
{f
ather :: get ( ) ;
mother :: get ( ) ;
cout << “child's name: “;
cin >> name;
cout << “child's standard”;
cin >> std;
}
void daughter :: show ( )
{f
ather :: show ( );
nfather :: show ( ) ;
cout << “In child’s name is : “ <<name;
cout << “In child's standard: “ << std;
}
main ( )
{
clrscr ( ) ;
daughter d1;
d1.get ( ) ;
d1.show ( ) ;
}
Hierarchical Inheritance
Another interesting application of inheritance is to use is as a support to a hierarchical
design of a
class program. Many programming problems can be cast into a hierarchy where
certain features of one level are shared by many others below that level for e.g.
23
// Program to show the hierarchical inheritance
#include<iostream.h>
# include<conio. h>
class father
//Base class declaration
{i
nt age;
char name [15];
public:
void get ( )
{
cout<< “father name please”; cin >> name; cout<< “father’s age please”; cin >> age;
}
void show ( )
{
cout << “In father’s name is ‘: “<<name;
cout << “In father’s age is: “<< age;
} };
class son : public father
//derived class 1
{
char name [20] ;
int age ;
public;
void get ( ) ;
void show ( ) ;
} ;
void son : : get ( )
{f
ather :: get ( ) ;
cout << “your (son) name please” << “in”; cin >>name;
cout << “your age please” << “ln”; cin>>age;
}
void son :: show ( )
{f
ather : : show ( ) ;
cout << “In my name is : “ <<name;
cout << “In my age is : “ <<age;
}
class daughter : public father
//derived class 2.
{
char name [15] ;
int age;
public:
void get ( )
{f
ather : : get ( ) ;
cout << “your (daughter’s) name please In” cin>>name;
cout << “your age please In”; cin >>age;
}
void show ( )
{f
ather : : show ( ) ;
cout << “in my father name is: “ << name << “
In and his age is : “<<age;
} };
24
main ( )
{c
lrscr ( ) ; son S1;
daughter D1 ;
S1. get ( ) ;
D1. get ( ) ;
S1 .show( ) ;
D1. show ( ) ;
}
25
EXPT. NO. 12 WRITE A PROGRAM ON CONTAINER CLASS
Containership in C++
When a class contains objects of another class or its members, this kind ofrelationship
is called containership or nesting and the class which contains objects of another class
as its members is called as container class. Syntax for the declaration of another class
is:
Class class_name1
{
——–
};
Class class_name2
{
——–
};
Class class_name3
{
Class_name1 obj1; // object of class_name1
Class_name2 obj2; // object of class_name2
———-
};
//Sample Program to demonstrate Containership
#include < iostream.h >
#include < conio.h >
#include < iomanip.h >
#include< stdio.h >
const int len=80;
class employee
{
private:
char name[len]; int number;
public:
void get_data()
{
cout << "\n Enter employee name: ";
cin >> name;
cout << "\n Enter employee number: ";
cin >> number;
}
void put_data()
{
cout << " \n\n Employee name: " << name;
cout << " \n\n Employee number: " << number;
} };
class manager
{
private:
char dept[len]; int numemp;
employee emp;
public:
void get_data()
{
emp.get_data();
cout << " \n Enter department: ";
cin >> dept;
cout << "\n Enter number of employees: ";
26
cin >> numemp;
}
void put_data()
{
emp.put_data();
cout << " \n\n Department: " << dept;
cout << " \n\n Number of employees: " << numemp;
} };
class scientist
{
private:
int pubs,year;
employee emp;
public:void get_data()
{
emp.get_data();
cout << " \n Number of publications: ";
cin >> pubs;
cout << " \n Year of publication: ";
cin >> year;
}
void put_data()
{
emp.put_data();
cout << "\n\n Number of publications: " << pubs;
cout << "\n\n Year of publication: "<< year;
} };
void main()
{
manager m1; scientist s1;
int ch;
clrscr();
do
{
cout << "\n 1.manager\n 2.scientist\n";
cout << "\n Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1:
cout << "\n Manager data:\n";
m1.get_data();
cout << "\n Manager data:\n";
m1.put_data();
break;
case 2:cout << " \n Scientist data:\n";
s1.get_data();
cout << " \n Scientist data:\n";
s1.put_data();
break;
}
cout << "\n\n To continue Press 1 -> ";
cin >> ch;
}
while(ch==1);
getch();
}
OUTPUT
27
EXPT. NO. 13 WRITE A PROGRAM ON VIRTUAL FUNCTIONS
Virtual Functions
Virtual functions, one of advanced features of OOP is one that does not really exist
but it« appears
real in some parts of a program. This section deals with the polymorphic features
which are
incorporated using the virtual functions.
The general syntax of the virtual function declaration is:
class use_detined_name{
private:
public:
virtual return_type function_name1 (arguments);
virtual return_type function_name2(arguments);
virtual return_type function_name3( arguments);
------------------
};
To make a member function virtual, the keyword virtual is used in the methods while
it is declared in
the class definition but not in the member function definition. The keyword virtual
precedes the
return type of the function name. The compiler gets information from the keyword
virtual that it is a
virtual function and not a conventional function declaration.
For. example, the following declararion of the virtual function is valid.
class point {
intx;
inty;
public:
virtual int length ( );
virtual void display ( );
};
Remember that the keyword virtual should not be repeated in the definition if the
definition occurs
outside the class declaration. The use of a function specifier virtual in the function
definition is
invalid.
For example
class point {
intx ;
inty ;
public:
virtual void display ( );
};
virtual void point: : display ( ) //error
{
Function Body
}
A virtual function cannot be a static member since a virtual member is always a
member of a
28
particular object in a class rather than a member of the class as a whole.
class point {
int x ;
int y ;
public:
virtual static int length ( ); //error};
int point: : length ( )
{
Function body
}
A virtual function cannot have a constructor member function but it can have the
destructor member
function.
class point {
int x ;
int y ;
public:
virtual point (int xx, int yy) ; // constructors, error
void display ( ) ;
int length ( ) ;
};
A destructor member function does not take any argument and no return type can be
specified for it
not even void.
class point {
int x ;
int y ;
public:
virtual point (int xx, int yy) ; //invalid
void display ( ) ;
int length ( ) ;
It is an error to redefine a virtual method with a change of return data type in the
derived class with
the same parameter types as those of a virtuall method in the base class.
class base {
int x,y ;
public:
virtual int sum (int xx, int yy ) ; //error
} ;
class derived: public base {
intz ;
public:
virtual float sum (int xx, int yy) ;
};
The above declarations of two virtual functions are invalid. Even though these
functions take
identical arguments note that the return data types are different.
virtual int sum (int xx, int IT) ; //base class
virtual float sum (int xx, int IT) ; //derived class
29
Both the above functions can be written with int data types in the base class as well as
in the derived class as virtual int sum (int xx, int yy) ; //base class
virtual int sum (int xx, int yy) ; //derived class Only a member function of a class can
be declared as virtual. A non member function (non method) of a class cannot be
declared virtual.
virtual void display ( ) //error, nonmember function
{
Function body
}
#include <iostream.h>
#include <conio.h>
class student {private:
introllno;
char name [20];
public:
virtual void getdata ( );
virtual void display ( );
};
class academic: public student {
private :
char stream[10];
public:
void getdata { };
void display ( ) ;
};
void student: : getdata ( )
{
cout<< “enter rollno\n”;
cin >> rollno;
cout<< “enter name \n”;
cin >>name;
}
void student:: display ( )
{
cout<< “the student’s roll number is”<<rollno<< “and name is”<<name;
cout<< end1;
}
void academic: : getdata ( )
{
cout << “enter stream of a student? \n”;
cin>> stream;
}
void academic:: display ( )
{
cout<< “students stream \n”;
cout<< stream << endl;
}
void main ( )
{ student *
ptr ;
academic obj ;
ptr = &obj ;
ptr->getdata ( );
ptr->dlsplay ( );
getch ( )
OUTPUT
Comments
Post a Comment