Beruflich Dokumente
Kultur Dokumente
COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY
HOD
PRINCIPAL
CORRESPONDENT
UNIT III
ADVANCED PROGRAMMING
Templates
Generic Programming
STL
Inheritance
Exceptions
OOP Using C++
PART-A
1. What is meant by exception? [M/J2016] [A/M2015] [M/J2014] [M/J2012] [or]
Mention the use of exception. [M/J2013]
2. What is a template? [A/M2015] [M/J2012]
3. What is class template? [M/J2014]
4. Define Inheritance. [M/J2013] [or] What is the use of inheritance? [N/D2014]
[N/D2013]
5. List the functions of Standard Template Library. [N/D2014]
6. Mention the advantages of using template functions and template classes.
[Nov/Dec-2012]
7. What is generic function (or) template function?
8. Write down the syntax for try block. [N/D2011]
9. Write the syntax for a function to catch all types of exceptions. [N/D2013]
10. Mention the advantages of using template functions and template classes.
[N/D2012]
11. What is generic programming? [M/J 2016]
PART-B
1. What is a function template? Write a template function to sort array of float and int
using bubble sort. (16m)[A/M2015] (16m)[M/J2012] (10m)[N/D2011] (8m) [N/D2012]
[or] What is a function template? Write a template function for finding the largest number
in a given array. The array parameter must be generic-data types. (16m)[M/J2014]
2. What is inheritance? List out the advantages of Inheritance.[M/J 2016] [7m] Write a
C++ program to implement multiple inheritance [M/J 2016][9m] Discuss the various
types of inheritance that are available in C++ with neat diagram. (16m)[A/M2015] (16m)
[M/J2013] (8m)[A/M2011]
NOTES
UNIT III
ADVANCED PROGRAMMING
PART A
1. What is meant by exception? [M/J2016] [A/M2015] [M/J2014] [M/J2012] [or]
Mention the use of exception. [M/J2013]
Exceptions are run time anomalies or unused conditions that a program may
encounter while executing. These anomalies can be division by zero, access to an array
outside of its bounds or running out of memory or disk space. The mechanism for
exception handling is,
1. Find the problem (hit the exception).
2. Inform that an error has occurred (throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).
2. What is a template? [A/M2015] [M/J2012]
Template enables us to define generic classes and function thus provides
support for generic programming. A template can be used to create a family of classes
or functions. For ex, a class template for an array class would enable us to create
arrays of various data types such as int array and float array.
3. What is class template? [M/J2014]
A class template is also known as a generic class, defines a group or a family of
classes having the same class definition but handling different type of data. While using
class templates, only one class definition needs to be created and the compiler
automatically generates the required classes for handling the individual data types.
4. Define Inheritance. [M/J2013] [or] What is the use of inheritance? [N/D2014]
[N/D2013]
5
Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification and
supports for reusability. The class which is inherited is known as the base or super
class and class which is newly derived is known as the derived or sub class.
5. List the functions of Standard Template Library. [N/D2014]
The STL provides a ready-made set of common classes for C++, such as
containers and associative arrays, that can be used with any built-in type and with any
user-defined type that supports some elementary operations (such as copying and
assignment). STL algorithms are independent of containers, which significantly reduces
the complexity of the library.
6. Mention the advantages of using template functions and template classes.
[Nov/Dec-2012]
of programming situations.
Generic programming is achieved by using template.
Here T type is a placeholder name for a data type used by the function. This name
may be used within the function definition.
8. Write down the syntax for try block. [N/D2011]
The general form is as follows:
9. Write the syntax for a function to catch all types of exceptions. [N/D2013]
10. Mention the advantages of using template functions and template classes.
[N/D2012]
Template is one of the added features in C++. In general itt enables us to define
generic classes and function thus provides support for generic programming. A template
can be used to create a family of classes or functions. For ex, a class template for an
array class would enable us to create arrays of various data types such as int array and
float array.
11. What is generic programming?[M/J 2016]
Generic programming is an approach of writing programs in which a generic type
is passed as a parameter in the definition of a function or a class sothat they can work
with different types of data.
12. What is the significance of Iterators? [N/D'2014]
Iterators are central to generic programming because they are an interface
between containers and algorithms: algorithms typically take iterators as arguments.
Iterators provide a means for accessing data stored in container classes such a vector,
map, list, etc.
13. What is the difference between a class template and an ordinary class?
Class Template
Ordinary Class
A class template define s a group or a The object with same data structure
family of classes having the same and behaviour are grouped into a
class definition but handling different class
type of data.
Syntax:
Syntax:
template<class T>
Class classname
class classname
};
};
14. Define STL and write its types.
needed.
Saves Time and Effort: The above concept of reusability achieved by
inheritance saves the programmer time and effort. Since the main code written
can be reused in various situations as needed.
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multiple inheritance
Hybrid inheritance
Example 2
template<class T>
void swap(T &x,T &y)
template<class T>
void bubble(T a[], int n)
10
{
T temp =x;
x=y;
y=temp;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter two int values:\n";
cin>>a>>b;
cout<<"Before swap:\n";
cout<<a<<"\t"<<b;
swap(a,b);
cout<<"\nAfter swap:\n";
cout<<a<<"\t"<<b;
cout<<"\nEnter two float values:\n";
cin>>c>>d;
cout<<"\nBefore swap:\n";
cout<<c<<"\t"<<d;
swap(c,d);
cout<<"\nAfter swap:\n";
cout<<c<<"\t"<<d;
getch();
}
The function template swap (T &x, T &y),
we no need to redefine for any other datatype values.
}
template<class x>
void swap(X &a, X &b)
{
X temp = a;
a=b;
b=temp;
}
int main()
{
int x[5] = {10,50,30,40,20};
Float y[5] = {1.1,5.5,3.3,4.2,2.2};
bubble(x,5);
bubble(y,5);
cout<<sorted x array:;
for(int i=0;i<5;i++)
cout<<x[i]<<;
cout<<endl;
cout<<sorted y array:;
for(int j=0;j<5;j++)
cout<<y[j]<<;
cout<<endl
return(0);
}
Output:
sorted x array: 10 20 30 40 50
sorted y array: 1.1 2.2 3.3 4.4 5.5
};
Example,
template<class T1,class T2>
void disp(T1 x, T2 y)
{
cout<<x<<y;
}
Void main()
{
disp(10,22.2);
disp(F,22);
disp(G,10.23);
}
2. What is inheritance? List out the advantages of Inheritance. [M/J 2016] [7m]
Write a C++ program to implement multiple inheritance [M/J 2016][9m] Discuss
the various types of inheritance that are available in C++ with neat diagram. (16m)
[A/M2015] (16m)[M/J2013] (8m)[A/M2011] (16m)[N/D2011] (16m)[N/D2012] [or]
Explain the different forms of Inheritance with an example. (16m) [N/D2014]
Inheritance
The mechanism of deriving a new class from an old one is called inheritance.
The old is referred to as the base class and the new one is called derived class or sub
class. C++ strongly supports the concept of reusability by means of inheritance. Once a
class has been written and tested. It can be adapted by other programmers to suit their
requirements.
Advantages of Inheritance:
It allows the code to be reused as many times as needed.
The base class once defined and once it is compiled, it need not be reworked.
12
Saves time and effort as the main code need not be written again.
Types of Inheritance
Multiple Inheritance - derive a class from more than one base class
Hierarchical Inheritance - a base class can have more than one derived class
..
}
The colon indicates that the derived class name is derived from the base class name.
The visibility mode is either private or public. The default visibility mode is private.
Example
Class ABC
{
};
Class XYZ : public ABC // public derived class
{..
}
Class ZXC: private ABC
{
..
};
Class XYZ is public derived class; we can derive another class from XYZ.
13
Class ZXC is private derived class; we cannot derive any more class from ZXC.
When a base class is privately inherited by a derived class, public members of
the base class become private member of the derived class and therefore the public
members of the base class can access only by the member function of the derived
class. They are inaccessible to objects of the derived class. Remember that public
members of a class can be accessed by dot operator. The result is that no public
member of the base class is accessible to the objects of the derived class.
When a base class is publicly inherited by a derived class, public members of
the base class become public members of the derived class and therefore they are
accessible to the objects of the derived class.
Example
class base
{
int a;
public:
int b;
int get()
{
cout<<"\nEnter two numbers:";
cin>>a>>b;
return a;
}
void put()
{
cout<<"\nBase class\n";
cout<<a<<"\t"<<b;
}
};
class derived:public base
{
int c;
public:
void add()
{
c=b+get(); // can access the public
member of class base
}
void dis()
{
cout<<"\nDerived Class";
cout<<"\nThe result is:"<<c;
}
};
void main()
{
clrscr();
base ob;
derived ob1;
ob1.add(); // can access the public
member of class derived
ob1.put();
// can access the public
member of class base
ob1.dis();
// can access the public
member of class derived
getch();
}
14
class
Protected
derivation
Not inherited
Public
Public
derivation
Not inherited
Protected
Protected
derivation
Not inherited
Private
Private
1. Single Inheritance
This type of inheritance uses only one base class and only one derived class.
Further, the derived class cannot act as base class.
In the given program, the base class is student and the derived class is
my_Information. Base class contains Student_ID, Name, and Contact_No as its public
data members and a constructor to initialize these members. The derived class contains
print_details() as its public member function.
Example
class Student
{
public:
int student_ID;
char name[15];
int contact_no;
public:
Student()
{
student_ID=1;
strcpy(name,"YOUR NAME");
contact_no=4288;
}
};
2. Multi level inheritance
15
Example,
class grandparent
{ protected:
char name[20];
grandparent()
{ strcpy(name,"grandparent_name");
}
void disp()
{
cout<<"\n Grandparent Name: "<<name;
}
};
class parent: public grandparent
{ protected:
int age;
public:
parent()
{
strcpy(name,"parent_name");
age=45;
}
void display()
{
cout<<"\n Parent Name: <<name<<"\tAge:
"<<age;
} };
3. Multiple Inheritance
16
When a class is derived from more than one class, then this type of inheritance is
called as Multiple Inheritance. Properties of various base classes are transferred to
single derived class.
The syntax of the derived class with multiple base classes is as follows:
Class D: visibility B1, visibility B2, visibility B3
{
Body of D
};
Example,
class M
{ protected:
int m;
public:
void get_m(int);
};
class N
{ protected:
int n;
public:
void get_n(int);
};
class P:public M, public N
{
public:
void display();
};
void M::get_m(int a)
{ m=a;
}
void N::get_n(int b)
{ n=b;
}
void P::display()
{ cout<<"\n m= "<<m;
cout<<endl<<" n= "<<n;
cout<<endl<<" m*n="<<m*n;
}
void main()
{ P p1;
clrscr();
p1.get_m(10);
p1.get_n(20);
p1.display();
getch();
}
17
Occasionally, we may face the problem in using the multiple inheritance, when a
function with the same name appears in more than one base class.
Example,
class M
{
public:
void disp()
{
cout<<"\nClass M";
}
};
class N
{
public:
void disp()
{
cout<<"\nClass N";
}
};
The statement M::disp() and N::disp() will resolve the ambiguity in multiple inheritance.
In single inheritance also this ambiguity will arise, it can be solve, the following
example shows,
class A
{
public:
void disp()
{
cout<<"\nClass A";
}
};
class B:public A
{
public:
void disp()
{
4. Hierarchical inheritance
cout<<"\nClass B";
}
};
void main()
{
clrscr();
B ob;
ob.disp(); // call the function in derived class B
ob.A::disp(); //Call the function in base class A
getch();
}
18
A single base class can be shared by several derived classes and this type of
inheritance is called as Hierarchical Inheritance. Hierarchical unit shows top down style
through splitting a compound class into several simple sub classes.
Example,
class green: public blue, public yellow
{
public:
green()
{
cout<<" =Green ";
}
};
class violet: public red, public blue
{
public:
violet()
{
cout<<" =Violet ";
}
};
class reddishbrown:public orange, public
violet
{
public:
reddishbrown()
{
cout<<" =Reddish Brown ";
}
};
5. Hybrid inheritance
19
Example,
class PLAYER
{
protected:
char name[15];
char gender;
int age;
};
class PHYSIQUE: public PLAYER
{
protected:
float height;
float weight;
};
class LOCATION
{
protected:
char city[10];
char pin[7];
};
class GAME: public PHYSIQUE, public
LOCATION
{
protected:
char game[15];
public:
void getdata()
{
cout<<"enter following information\n";
cout<<"NAME :";
cin>>name;
cout<<"GENDER:";
cin>>gender;
cout <<"AGE:";
cin>>age;
cout<<"HEIGHT:";
cin>>height;
cout<<"WEIGHT:";
cin>>weight;
cout<<"CITY:";
cin>>city;
cout<<"PINCODE:";
cin>>pin;
cout<<"GAME:";
cin>>game;
}
void show()
{
cout<<"\nentered information\n";
cout<<"\nNAME :";
cout<<name;
cout<<"\nGENDER:"; cout<<gender;
cout <<"\nAGE:";
cout<<age;
cout<<"\nHEIGHT:"; cout<<height;
cout<<"\nWEIGHT:"; cout<<weight;
cout<<"\nCITY:";
cout<<city;
cout<<"\nPINCODE:"; cout<<pin;
cout<<"\nGAME:";
cout<<game;
}
};
void main()
{
clrscr();
GAME G;
G.getdata();
G.show();
getch();
}
20
and to throw exceptions, and other to catch the exceptions and to take appropriate
action.
Why Exception Handling?
Following are main advantages of exception handling over traditional error handling.
1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling becomes
separate from the normal flow.
2) Functions/Methods can handle any exceptions they choose: A function can
throw many exceptions, but may choose to handle some of them. The other exceptions
which are thrown, but not caught can be handled by caller. If the caller chooses not to
catch
them,
then
the
exceptions
are
handled
by
caller
of
the
caller.
In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way (either by specifying it
again or catching it)
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as
exception. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes, categorize them according to types.
22
When the try block throws the exception, the program control leaves the try block
and enters the catch block. Note that the exceptions are thrown in the form of object. If
the type of object thrown matches the arg in catch block, the statement inside the catch
block is executed. If the thrown object not match with the arg in catch block then the
23
program is aborted with the help of abort() function that will invoked by the compiler
automatically.
When no exception is detected and thrown, the control goes to the statement
immediately after the catch block, that is the catch block is skipped.
Example,
void main()
{
int a,b,c;
clrscr();
cin>>a>>b;
c=a-b;
try
{
if(c==0)
{
throw(c);
}
else
cout<<a/b;
}
catch(int i)
{
cout<<"\nException caught");
}
getch();
}
On running the program, when exception is detected the exception is thrown, the
catch block catches the exception and executes the statement inside the catch block. If
no exception is thrown the catch block is skipped and control goes to next to the catch
block.
The following illustrates the function invoked by the try block throwing exception,
24
Throw(object);
}
..
..
Try
{
..
..
Invoke function here;
..
}
Catch(type arg)
{
Example
void divide(int a,int b)
{
int c;
try
{
if(b==0)
{
throw(b);
}
else
{
c=a/b;
cout<<c;
}
}
catch(int i)
{
cout<<"Exception caught";
}
}
void main()
{ int a,b;
cin>>a>>b;
divide(a,b);
}
25
Throwing mechanism
When an exception that is desired to be handled is detected, it is thrown using
the throw statement in any one of the following:
throw(exception);
throw exception;
throw;
The operand exception may be of any type. When an exception is thrown, it will
be caught by the catch statement associated with the try block.
Catching mechanism
Code for handling exception is included in catch blocks. A catch block looks like a
function definition and is the form,
catch(type arg)
{
Handles the exception;
}
The catch statement catches an exception whose type matches with the type of
catch argument. When it is caught, the code in the catch block is executed.
It is important to note that the catch block is simply skipped if the catch statement
does not catch an exception.
throw exception;
..
..
}
Catch(type1 arg)
{
..
..
}
Catch(type2 arg)
{
..
..
}
.
Catch(typeN arg)
{
..
..
}
.
Example,
void find(int a)
{
try
{
if(a==0)
throw(10);
else if(a==10)
throw('A');
else
throw(1.2);
}
catch(int x)
{
cout<<"Integer Exception caught"<<x;
}
catch(char x)
{
cout<<"character Exception caught"<<x;
}
catch(double x)
{
cout<<"Double Exception caught"<<x;
}
}
void main()
{
int a;
cin>>a;
find(a);
}
Example,
27
void fun(int a)
{
if(a==10)
throw (1);
else if(a==1)
throw(1.2);
else
throw ('A');
}
void main()
{
int a;
cin>>a;
try
{
fun(a);
}
catch(...)
{
cout<<"Exceeption caught";
}
}
Specifying an exception
It is possible to restrict a function to throw only certain specified exceptions. This
is achieved by adding a throw list clause to the function definition. The general form is
shown below,
Type function (arg list) throw (type-list)
{
..
Function body
}
The type-list specifies the type if exception that the function has to throw.
Throwing any other type of exception will cause an abnormal termination of the
28
catch(int x)
{
cout<<x;
}
catch(char x)
{
cout<<x;
}
catch(double x)
{
cout<<x;
}
}
4. Explain the Template and Class Template with an example program. (8m)
[N/D2014] (16m)[N/D2013]
A key problem in programming is programmer productivity. An important
technique is code reuse. Generic programming is a critical methodology for enhancing
code reuse. Generic programming is about code that can be used over a wide category
of types. In C++, there are three different ways to employ generic coding techniques:
void* pointers, templates, and inheritance. This lets us concentrate on C++ templates
and how they are used effectively.
C++ has template functions that can be used to create generic code. Template
functions are written using the keyword template followed by angle brackets. The angle
brackets contain an identifier that is used as a placeholder for an arbitrary type. C++
uses the keyword template to provide parametric polymorphism, which allows the same
29
code to be used with respect to various types, in which the type is a parameter of the
code body. This is a form of generic programming. The syntax of the template class
declaration is prefaced by,
template <class identifier>
This identifier is a template argument that essentially stands for an arbitrary type. This
argument is instantiated in the declarations.
Templates
Template is one of the added features in C++. It enables us to define generic
classes and function thus provides support for generic programming. A template can
be used to create a family of classes or functions. For ex, a class template for an
array class would enable us to create arrays of various data types such as int array and
float array.
A template can be considered as a kind of macro. When a template is defined
with a parameter that would be replaced by a specified at the time of actual use of the
class or function, the templates are sometimes are called as parameterized classes or
functions.
Class templates
A class template is also known as a generic class, defines a group or a family of
classes having the same class definition but handling different type of data. It is a
simple process to create a generic class using the template with an anonymous type.
The general format of a class template is,
Template<class T>
Class classname
{
//class member specification with anonymous type T
};
The class created from a class template is called a template class. The syntax for
defining an object of a template class is:
30
Example 2
Template<class T>
class calculator
{
T a,b;
public:
void getdata(T x,T y)
{
a=x;
b=y;
}
T add()
{
return a+b;
}
T diff()
{ return a-b;
}
T prod()
{ return a*b;
}
T quotient()
{ return a/b;
}
void display()
{
cout<<The two numbers are: << a<<and
<<b;
cout<<Sum : <<add();
cout<<Difference : <<diff();
cout<<Product : <<prod();
cout<<Quotient : <<quotient();
}
};
31
In the above example 1, the template class is sample, in the constructor, we can add
any numeric data type values. No need to redefine the class for adding various data
types. The same template class can be used to add any numeric data type values.
Class template with multiple parameters
We can design the class template with the multiple parameters. The general form is
shown below,
Template<class T1,class T2,..,class Tn>
Class classname
{
//class member specification with anonymous type T
};
The syntax for defining an object of a template class with multiple parameter is:
Classname <type1,type2,typen> objectname(arglist);
Example,
template<class T1,class T2>
class sample
{
T1 a;
T2 b;
public:
sample(T1 x,T2 y)
{
a=x;
b=y;
}
void disp()
{
cout<<a<<"\t"<<b<<"\n";
}
};
void main()
{
clrscr();
sample <int,float> ob(10,20.233);
sample <float,char> ob1(11.2333,'A');
cout<<"for the first type:\n";
ob.disp();
cout<<"for the second type:\n";
ob1.disp();
getch();
}
The statement; template<class T1,class T2>, the class sample can adopt any two
different data type values.
32
sample <int,float> ob(10,20.233); will invoke the constructor, and assigns the value to
the variable a and b respectively.
sample <float,char> ob1(11.2333,'A'); will invoke the constructor, and assigns the value
to the variable a and b respectively.
5. Explain Overloading of Template functions.
A template function may be overloaded either by template functions or ordinary
functions of its name. in such cases, the overloading resolution is accomplished as
follows:
Try normal overloading resolution to ordinary functions and call the one that
matches.
33
6. What is virtual base class? Create a situation where you will use virtual base
class [M/J2007]
Virtual base class
Consider a situation where all the three kinds of inheritance, namely, multilevel,
multiple and hierarchical inheritance are involved. This is illustrated in the following
figure:
Inheritance by the child as shown in the above figure might pose some problems. All the
public and protected members of grandparent are inherited into child twice, first via
parent 1 and second via parent 2. This means child would have duplicate set of the
members inherited from the grand parent. This introduces ambiguity and it should be
34
avoided. The duplication of the inherited members due to these multiple paths can be
avoided by making the common base class as virtual base class while declaring the
direct or intermediate base classes as shown below,
Class A
{
..
..
};
Class B:public virtual A
{
..
..
};
Class C:virtual public B
{
..
..
};
Class D:public B,public C
{
..
.. / only one copy of A will be inherited
};
Example,
35
class student
{
protected:
int rollno;
public:
void get_rno()
{
cout<<"\nEnter Roll number:";
cin>>rollno;
}
void put_rno()
{
cout<<"\nRoll Number is:"<<rollno;
}
};
class test: virtual public
student
//derived as virtual
{
protected:
int m1,m2;
public:
void get_ma()
{
cout<<"\nEnter Two marks:";
cin>>m1>>m2;
}
void put_ma()
{
cout<<"\nSubject Marks
are:"<<m1<<"\t"<<m2;
}
};
class sports: virtual public
student //derived as virtual
protected:
int spmarks;
public:
void get_sp()
{
cout<<"\nEnter Soprt marks:";
cin>>spmarks;
}
void put_sp()
{
cout<<"\nSport Mark is:"<<spmarks;
}
};
class result: public test, public sports
{
int total;
public:
void tot()
{
total=m1+m2+spmarks;
}
void disp()
{
put_rno();
put_ma();
put_sp();
cout<<"\nThe total is:"<<total;
}
};
void main()
{
result ob;
clrscr();
ob.get_rno();
ob.get_ma();
ob.get_sp();
ob.tot();
ob.disp();
getch();
}
36
Abstract classes
An abstract class is one that is not used to create objects. An abstract class is
designed only to act as a base class (to be inherited by other classes). In the previous
example, the student class is an abstract class since it was not used to create any
objects.
7. What is virtual function? When do you use a pure virtual function? Differentiate
them [M/J2007]
Virtual function
The ability to refer to objects without any regard to their classes that means the
use of a single pointer variable to refer to the objects of different classes. Here we
use the pointer to base class to refer to all the derived objects. When we use the same
function name in both derived and base class, the function in the base class is declared
as virtual preceding the function definition. When a function is made virtual, C++
determines which function has to invoke depends on the objects that is being referred to
base class pointer
The general form is,
Virtual Return-type fn-name(arglist)
{
}
Here the virtual is the keyword, the fn-name should same in both of the base and
derived class as below:
Class base
{
Public:
Virtual void add()
{
..
}
};
Class derived: public base
{
37
Public:
void add()
{
..
}
};
Just define the object for base and derived and pointer object to base class. Just as
below:
Base *ptr;
Base ob;
Derived ob1;
Ptr=&ob;
Ptr->add();
In the above, the base class object is assigned to ptr, ptr->Add() will call the fn in
base class.
Ptr=&ob1;
Ptr->add();
In the above, the derived class object is assigned to ptr, ptr->Add() will call the fn
in derived class.
Rules for Virtual function
A virtual function in the base class must be defined even though it is not used.
The prototype of the base and derived class version should be identical.
38
Example,
class base
{
public:
int a;
void disp()
{
cout<<"\nBase class";
}
virtual void show()
{
a=10;
cout<<"\nA="<<a;
}
};
class derived: public base
{
public:
int b;
void disp()
{
cout<<"\nDerived Class";
}
void show()
{
b=20;
cout<<"\nB="<<b;
}
};
void main()
{
clrscr();
base *ptr;
base ob;
derived ob1;
ptr=&ob; //assign the base class object
ptr->disp(); //call the fn in base class
ptr->show(); //call the fn in base class
ptr=&ob1; //assign the derived class object
ptr->disp(); //try to call the fn in derived
class,but it won't because fn is not virtual
ptr->show(); //call the fn in derived class,
because it is virtual fn
getch();
}
39
This function is call as pure virtual function. A pure virtual function is a function
declared in a base class that has no definitions relative to the base class. In such cases,
all the derived class should define the function or redeclare the function as pure virtual
function.
A class containing pure virtual function cannot be used to declare any objects of
its own. Such classes are call as abstract class. We can achieve the rum time
polymorphism by declaring the pointer object to the base class and assign the address
of the derived classes.
Example,
class base
{
public:
virtual void disp()=0; //pure
function declaration
};
class derived1:public base
{
public:
void disp()
{
cout<<"Derived class1";
}
};
class derived2:public base
{
public:
void disp()
{
cout<<"\nDerived class2";
}
};
void main()
{
virtual
base *ptr;
derived1 ob1;
derived2 ob2;
clrscr();
ptr=&ob1; //assign derive1 object
ptr->disp();
ptr=&ob2; //assign derive2 object
ptr->disp();
getch();
}
40
41
42