You are on page 1of 66

Mailam Engineering College, Mailam.

Department of Information Technology


(CS2311/U-II)

UNIT - II

Syllabus:

Operator overloading - friend functions- type conversions- templates - Inheritance –


virtual functions- runtime polymorphism.

PART – A

1. What are Friend functions? Write the syntax [Nov/Dec 2013]

A function that has access to the private member of the class but is not itself
a member of the class is called friend functions.

The general form is

friend data_type function_name( );

Friend function is preceded by the keyword „friend‟.

2. Write some properties of friend functions.


 Friend function is not in the scope of the class to which it has been
declared as friend. Hence it cannot be called using the object of that
class.
 Usually it has object as arguments.
 It can be declared either in the public or private part of a class.
 It cannot access member names directly. It has to use an object name
and dot membership operator with each member name. eg: ( A . x )
3. What are virtual functions?

A function qualified by the „virtual‟ keyword is called virtual function. When


a virtual function is called through a pointer, class of the object pointed to
determine which function definition will be used.

4. Write some of the basic rules for virtual functions


 Virtual functions must be member of some class.
 They cannot be static members and they are accessed by using object
pointers
 Virtual function in a base class must be defined.
 Prototypes of base class version of a virtual function and all the derived
class versions must be identical.
 If a virtual function is defined in the base class, it need not be redefined
in the derived class.
5. What are pure virtual functions? Write the syntax.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 1
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

A pure virtual function is a function declared in a base class that has no


definition relative to the base class. In such cases, the compiler requires
each derived class to either define the function or redeclare it as a pure
virtual function. A class containing pure virtual functions cannot be used to
declare any object of its own. It is also known as “do-nothing” function.

The “do-nothing” function is defined as follows:

virtual void display ( ) =0;

6. What is polymorphism? What are its types?

Polymorphism is the ability to take more than one form. An operation may
exhibit different behaviors in different. The behavior depends upon the type
of data used. Polymorphism is of two types. They are

 Function overloading
 Operator overloading

7. What is function overloading? Give an example.

Function overloading means we can use the same function name to create
functions that perform a variety of different tasks.

Eg: An overloaded add ( ) function handles different data types as shown


below. // Declarations

i. int add( int a, int b); //add function with 2 arguments of same type

ii. int add( int a, int b, int c); //add function with 3 arguments of same type

iii. double add( int p, double q); //add function with 2 arguments of different
type

//Function calls

add (3 , 4); //uses prototype ( i. )

add (3, 4, 5); //uses prototype ( ii. )

add (3 , 10.0); //uses prototype ( iii. )

8. What is operator overloading? [Nov/Dec 2013]

C++ has the ability to provide the operators with a special meaning for a
data type. This mechanism of giving such special meanings to an operator is
known as Operator overloading. It provides a flexible option for the creation
of new definitions for C++ operators.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 2
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

9. List out the operators that cannot be overloaded.


 Class member access operator (. , .*)
 Scope resolution operator (::)
 Size operator ( sizeof )
 Conditional operator (?:)
10. What is the purpose of using operator function? Write its syntax.
[Nov/Dec 2013]

To define an additional task to an operator, we must specify what it means


in relation to the class to which the operator is applied. This is done by
Operator function, which describes the task. Operator functions are either
member functions or friend functions. The general form is

return type classname :: operator (op-arglist )

function body

where return type is the type of value returned by specified operation.

Op-operator being overloaded. The op is preceded by a keyword operator.


operator op is the function name.

11. Write at least four rules for Operator overloading.


 Only the existing operators can be overloaded.
 The overloaded operator must have at least one operand that is of
user defined data type.
 The basic meaning of the operator should not be changed.
 Overloaded operators follow the syntax rules of the original operators.

They cannot be overridden.

12. How will you overload Unary & Binary operator using member
functions?

When unary operators are overloaded using member functions it takes no


explicit arguments and return no explicit values.

When binary operators are overloaded using member functions, it takes one
explicit argument. Also the left hand side operand must be an object of the
relevant class.

13. How will you overload Unary and Binary operator using Friend
functions?

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 3
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

When unary operators are overloaded using friend function, it takes one
reference argument (object of the relevant class) When binary operators are
overloaded using friend function, it takes two explicit arguments.

14. How an overloaded operator can be invoked using member functions?

In case of Unary operators, overloaded operator can be invoked as

op object_name or object_name op

In case of binary operators, it would be invoked as

Object . operator op(y)

where op is the overloaded operator and y is the argument.

15. How an overloaded operator can be invoked using Friend functions?

In case of unary operators, overloaded operator can be invoked as

Operator op (x);

In case of binary operators, overloaded operator can be invoked as

Operator op (x , y)

16. List out the operators that cannot be overloaded using Friend
function.
 Assignment operator =
 Function call operator ( )
 Subscripting operator [ ]
 Class member access operator (.)

17. What is meant by casting operator and write the general form of
overloaded casting operator.

A casting operator is a function that satisfies the following conditions

 It must be a class member.


 It must not specify a return type.
 It must not have any arguments.

The general form of overloaded casting operator is

operator type name ( )

{
Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 4
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

……….. // function statements

It is also known as conversion function.

18. Explain basic to class type conversion with an example.

Conversion from basic data type to class type can be done in destination
class. Using constructors does it. Constructor takes a single argument
whose type is to be converted.

Eg: Converting int type to class type

class time

int hrs,mins;

public:

………….

Time ( int t) //constructor

hours= t/60 ; //t in minutes

mins =t % 60;

};

Constructor will be called automatically while creating objects so that this


conversion is done automatically.

19. Explain class to basic type conversion with an example.

Using Type Casting operator, conversion from class to basic type conversion
can be done. It is done in the source class itself.

Eg: vector : : operator double( )

double sum=0;

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 5
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

for(int I=0;I<size;I++)

sum=sum+v[ i ] *u[ i ] ;

return sqrt ( sum ) ;

This function converts a vector to the corresponding scalar magnitude.

20. Explain one class to another class conversion with an example.

Conversion from one class type to another is the combination of class to


basic and basic to class type conversion. Here constructor is used in
destination class and casting operator function is used in source class.

Eg: objX = objY

objX is the object of class X and objY is an object of class Y. The class Y type
data is converted into class X type data and the converted value is assigned
to the obj X. Here class Y is the source class and class X is the destination
class.

21. What is meant by inheritance?

Inheritance is the process by which objects of one class acquire the


properties of another class. It supports the concept of hierarchical
classification. It provides the idea of reusability. We can add additional
features to an existing class without modifying it by deriving a new class
from it.

22. What is meant by single inheritance?

If a single class is derived from a single base class is called single


inheritance.

Eg:

Base class

Derived class

Here class A is the base class from which the class D is derived. Class D is
the public derivation of class B hence it inherits all the public members of B.
But D cannot access private members of B.

23. What is multiple inheritance?

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 6
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

If a class is derived from more than one base class, it is called multiple
inheritance.

Eg: Base classes

Derived class

Here class C is derived from two base classes A & B.

24. What is hierarchical inheritance?

If a number of classes are derived from a single base class then it is called
hierarchical inheritance.

Eg : Hierarchical classification of students in University

25. What is multilevel inheritance?

If a class is derived from a class, which in turn is derived from another class,
is called multilevel inheritance. This process can be extended to any number
of levels.

Eg:

Base class Grand father

Intermediate

Base class Father

Derived class Child

26. What is hybrid inheritance?

It is the combination of one or more types of inheritance.

Multilevel inheritance

Multiple inheritance

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 7
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

The class result will have both the multilevel and multiple inheritances.

Student

Arts Engineering Medical

CSE ECE Civil

Student

Test

Result

Sports

27. What is meant by Abstract base class?

A class that serves only as a base class from which derived classes are
derived. No objects of an abstract base class are created. A base class that
contains pure virtual function is an abstract base class.

28. Write short notes on virtual base class.

A base class that is qualified as virtual in the inheritance definition. In case


of multiple inheritances, if the base class is not virtual the derived class will
inherit more than one copy of members of the base class. For a virtual base
class only one copy of members will be inherited regardless of number of
inheritance paths between base class and derived class.

Eg: Processing of students‟ results. Assume that class sports derive the roll
number from class student. Class test is derived from class Student. Class
result is derived from class Test and sports.

As a virtual base class As a virtual base class

29. Define Polymorphism?

Polymorphism is the feature that allows one interface to be used for a


general class of actions. (ie) “one interface multiple methods”. This means
that it is possible to design a generic interface to a group of related activities.
This helps reduce complexity by allowing the same interface to be used to
specify a general class of action.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 8
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

30. Advantages of using template?


 It support resuability of code which elimates redundant coding
 Efficiency is one important usage of template function. A single
template functin is defined to work with different data types.
 Flexibility is another important advantages of using templates
31. Advantages of using inheritance
 Extend the functionality of an exisitng class
 It offers resuability of code
 No need to create objects from scratch
 C++ provides us mapping of real world hierrachy in our program
 Rsuable software component ca be developed
 It reduces software development time and cost considerably

PART - B

1. Explain the following concepts in detail

 Restrictions under operator overloading


 Operators which cannot be overloaded
 Operators which cannot be overloaded as friends
 Operator overloading: “The process of giving an existing operator a new
additional meaning is called operator overloading.”
 Restrictions under operator overloading:
 Operators should not lose their original meaning when overloaded.
 New operators cannot be devised.
 Operator cannot change number of arguments which are available in the
original form.
 Operators will have additional meaning, but will not have additional
precedence.
 Operators can only be overloaded for user-defined types.
 Operators which cannot be overloaded:
 The dot operator for member access.
 Dereference member to class operator(.*)
 Scope resolution operator(::)
 Sizeof operator(sizeof)
 Conditional ternary operator(?:)

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 9
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

 Casting operators: static_cast<>,dynamic_cast<>,const_cast<>


 # and ## Tokens for macro preprocessors
 Operators which cannot be overloaded as friends:
 Assignment operator(=)
 Function call operator()
 Array subscript operator[ ]
 Access to class member using pointer to object operator (->)
2. Write a C++ program to overload unary and binary operator.

Definition:

Operator overloading is performed by adding special member function to the


class which are known as operator functions. It is used to convert one object into
another. The operator function can be used as either member function or a friend
function. The operator function describes the action to be performed by the
operator.

Syntax:

Member function in class:

return type operator operator-symbol(arglist)

Friend function in class:

friend return type operator operator-symbol(arglist)

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 10
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

OPERATOR TYPE MEMBER FUNCTION FRIEND FUNCTION

Unary no argument one reference object as


argument

Binary one argument two reference object as


argument

Example:

Overloading unary minus

# include <iostream> void space: : operator-( )

using namespace std; {

class space x = -x;

{ y = - y;

int x; z = -z;

int y; }

int z; int main( )

public: {

void getdata(int a, int b, int c); space S;

void display(void); s.getdata(10, -20, 30);

void operator-( ); cout<<”S : “;


//overload unary minus
-S;
}; //activates operator – ( ) function

void space: : getdata (int a, int b, int c){ cout<<”-S : “;

x=a; S.display( );

y=b; return 0;

z=c; }

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 11
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

void space: : display (void) OUTPUT

{ S: X = 10 Y = -20 Z= 30

cout<<”x=”<<x<<” “; -S: X = -10 Y= 20 Z= -30

cout<<”y=”<<y<<” “;

cout<<”z=”<<z<<”\n “;

Overloading binary minus

# include<iostream> int main( )


using namespace std; {
class complex complex C1,C2,C3;
{ //invokes constructor 1
float x; C1=complex (2.5, 3.5);
//real part //invokes constructor 2
float y; C3=C1 + C2;
//imaginary part
public: cout<<”C1 = “;C1.display( );
complex( ) { } cout<<”C2 = “;C2.display( );
//Constructor 1 cout<<”C3 = “;C3.display( );
complex(float real, float imag) return 0;
//constructor 2 }
{ OUTPUT
x=real; y=imag; C1=2.5 + j3.5
} C2=1.6 + j2.7
complex operator + (complex); C3=4.1+j6.2
void display(void);
};
complex complex : : operator + (complex
c)
{
complex temp;
// temporary
temp.x= x + c.x;
temp.y=y + c.y;
return(temp);
}
void complex : : display(void)
{
cout<<x<<” + j “<<y<<”\n”;
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 12
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

3. Write a C++ program to perform overloading through friend function.

Definition: “Friend functions may be used in the place of member functions for
overloading a binary operator, the only difference being that a friend function
requires two arguments to be explicitly passed to it, while a member function
requires only one.”

Example:

# include<iostream> Matrix operator*(Matrix TempMatrix,


class Matrix int Multiplier)
{ {
int Element [3] [3]; for(int i=0;i<3;i++)
public: for(int j=0;j<3;j++)
Matrix( ) { }; TempMatrix. Element[i] [j] =
Matrix(int TempMatrix [3] [3]) Multiplier * TempMatrix. Element[i] [j];
{ return Matrix(TempMatrix.
for(int i=0;i<3;i++) Element);
for(int j=0;j<3;j++) }
} Matrix operator*( int Multiplier
void Read( ) ,Matrix TempMatrix)
{ {
for(int i=0;i<3;i++) for(int i=0;i<3;i++)
for(int j=0;j<3;j++) for(int j=0;j<3;j++)
cin>>element[i] [j]; TempMatrix. Element[i] [j] =
} Multiplier * TempMatrix. Element[i] [j];
void Display( ) return Matrix(TempMatrix.
{ Element);
for(int i=0;i<3;i++) }
{ void main( )
for(int j=0;j<3;i++) {
{ int ArrayofInt1 [ ] [3]={1,2,3,4,5,6,7,8,9};
cout<<Eleme int ArrayofInt2 [ ] [3]={4,5,6,7,8,9,1,2,3};
nt[i] [j]<<” “; Matrix M1 (ArrayofInt1);
} Matrix M2 (ArrayofInt2);
} Matrix M3, M4;
} M1.Dispaly ( );
friend Matrix operator*(Matrix, int); M3=M1*5;
friend Matrix operator*(int, Matrix); M3.Display ( );
}; M2.Display ( );
M4=5*M2;
M4.Display ( );
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 13
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

4. Write a C++ program to overload assignment operator.

 Overloading assignment operator is useful in various circumstances:


1. when we have dynamic constructors (which use dynamic allocation)
and
2. Destructor
Example:

#include<iostream> void Assignment::operator =


(Assignment as)
class Assignment
{
{
x=as.x;
int x;
}
public:
void main()
Assignment(){}
{
Assignment(int y)
Assignment a1(10);
{
Assignment a2;
x=y;
a2=a1;
}
a2.print();
void operator =(Assignment);
}
void print()
OUTPUT;
{
X: 10
cout<”X:”<<x;

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 14
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

5. Write a program to overload = operator. Assign values of data members of


one object to another object of the same type. Nov/Dec 2009

Refer Q.No:4

Overloading << and >>operator using frined

#include<iostream> istream & operator >> (istream &in,


Sample &s)
class Sample
{
{
in>>s.a;
int a;
return in;
public:
}
friend ostream & operator <<
(ostream &out, Sample &s); void main()

// operator function {

friend ostream & operator Sample s1;


>>(istream &in, Sample &s);
cin>>s1;
// operator function
cout<<s1;
};
}
ostream & operator <<(ostream
OUTPUT:
&out, Sample &s)
12
{
a:12
out<<”a:”;

out<<s.a;

return out; }

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 15
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

6. Write a C++ program that takes two values of time (hr, min, sec) and output
their sum using constructors and operator overloading (Nov/Dec 2009)

PROGRAM:

#include<iostream> // setting the value of the


using namespace std; second
class time void setSecond(int s)
{ {
int hr; if(s>=0 &&s<=60)
int min; sec=s;
int sec; else
public: sec=1;
Time ( ) { }
hr=0; // getting the value of day
min=0; int getHour()
sec=0; {
cout<<”Default constructor”); cout<<”Enter hour:”
} cin>>hr;
Time (int hr1, int min1) }
{ //getting the value of month
hr=hr1; int getMinute()
min=min1; {
sec=0; cout<<”Enter minute:”
cout<<”Parameterized cin>>min;
constructor”; }
} //getting the value of year
Time (int hr2, int min2, int int getSecond()
sec2) {
{ cout<<”Enter second:”
hr=hr2; cin>>sec;
min=min2; }
sec=sec2; Time operator +(Time &t)
cout<<”Parameterized {

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 16
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

constructor”; Time tmp;


} tmp.hr=hr+t.hr;
~Time() tmp.min=min+t.min;
{ tmp.sec=sec+t.sec;
cout<<”The object is destroyed”; return tmp;
} }
void display( ) };
{ void main ( )
cout<<”Time is “<<hr<<”Hours : {
“<<min<<”Minutes: and Time t1, t2, t3;
“<<sec<<”Seconds \n”; t1.getHour();
} t1.getMinutes();
t1.getSeconds();
//setting the value of the day t2.getHour();
int setHour(int h) t2.getMinutes();
{ t2.getSeconds();
if(h>=0 && h<24)
hr=h; t1.display();
else t2.dsiplay();
hr=1;
} t3=t1+t2;
// setting the value of minutes t3.display();
void setMinute(int m)
{ }
if(m>=0 && m<=60)
min=m;
else
min=1;
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 17
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

7. Write a C++ program that takes (x,y) co-ordinates of two points and output
the distance between them using constructors. Nov/Dec 2009

PROGRAM:

class point void main( )


{ {
int x,y; point
public: P1(10,20),P2(30,40);
point(x1,y1) point P3;
{ P3.distance(P1,P2);
x=x1,y=y1; }
}
void distance(point a, point b)
{
float dis=sqrt((pow(a.x-b.x),
2+pow(a.y-b.y),z))
cout<<dis;
}

`
8. Explain Type conversion using suitable C++ coding

 Type Conversion
o Definition: “when constants and variables of different types are
mixed in an expression. An assignment operation can be applied for
automatic type conversion. The type of data to the right of an
assignment operator is automatically converted to the type of the
variable on the left is called as type conversion”

o User defined conversion
o Wrapper class
o Built –in data type conversion
 User Defined conversion
o Definition: When we need to convert between different types, we can
guide the complier how to convert from one type to another by writing
operator function or constructor.
 Wrapper Class

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 18
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

o Definition: A class which makes a C like struct or built in data type


represent a data type int as a class.
 Built-in data type conversion:
o Definition: The conversion made with a built is a type is referred as
built in type conversion.
 Three type of situations that arise in the data conversion between
incompatible type:
1. Conversion from basic type to class type.

2. Conversion from class type to basic type.

3. Conversion from one class type to another class type.

 User defined conversion:


“When we need to convert between different types, we can guide the compiler
how to convert from one type to another by writing operator functions or
constructor. This constructors in operator functions in this case are known as user
defined conversion.”

Basic to Class Type

To convert data from a basic types to a user-defined type, the conversion function
should be defined in user-defined object‟s class in the form of the constructor.

Syntax

constructor(Basic Type)

……………..

……………..

Class Type to Basic Type

It converts the data members of an object to basic data types and returns a basic
data item.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 19
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Syntax:

Operator typename()

----

A conversion operator function is a function that satisfies the following conditions

 it must be a member function


 it must not specify a return type
 it must not have any arguments

PROGRAM

#include<string.h> #include<iostream.h>

#include<math.h> class Cartesian

class Cartesian; {

class Polar double x;

{ double y;

double radius; public:

double angle; Cartesian(double tx=0, double ty=0)

public: {

Polar(double tradius=0, double x=tx;


tangle=0)
y=ty;
{
}
radius=tradius;
Cartesian(Polar polarpoint)
angle=tangle;
{
}
double
double getradius() tr=polarpoint.getradius();

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 20
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

{ double
ta=polarpoint.getangle();
return radius;
x=tr*cos(ta);
}
y=tr*sin(ta);
double getangle()
}
{
operator polar()
return angle;
{
}
double ta=atan(x/y);
void show()
double tr=sqrt(x*x+y*y);
{
return polar(tr,ta);
cout<<”(“<<radius<<”,”<<angle<
<”)\n”; }

} void show()

}; {

cout<<”(”<<x<<”,”<<y<<”)\n”;

};

9. Explain about template with an example. (Nov/Dec 2009)

TEMPLATE
Definition:
”C++ supports a mechanism known as templates to implement the concept of
generic programming. Template allows us to generate a family of classes or family
of function to handle different data type. Template classes and function illuminate
code duplication for different types and thus make program development easier and
manageable”.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 21
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Two specifications:
1. Class template
2. Function template

1. Function Template
Definition:
” The generic function outlined by specification of a generic type using template
keyword. The actual function is defined later using the template”.
Format:
template<class T>
return type function name (arguments of typeT)
{
//
//body of the function with type T
//wherever appropriate
};
Where template is a keyword , typename T is a template data type.

Need for Function Template:


 Function Template is generic function which works for any data type that is
passed to them.
 The data type need not to be specified while writing the function.
 When using the template function, we can pass the data type and get the
required functionality.
 Also it is possible that we may not specify the data type and the compiler
deduces it for us
Drawbacks of using Macros in C++ Programs:
 Macros are not visible to the compiler.
 The type related information is lost in the macros.
 Macros are evaluated twice. Once when they are copied and the next time
when they are executed.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 22
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Advantages of using Templates


 It supports reusability of code which eliminates redundant coding.
 More efficient
 No run time overhead
 It provides flexibility because template function is used for different data types
also

1.1 The following program illustrates the concept of function template:


Program: Bubble Sort
# include <iostream> }
# include <conio> void main( )
using namespace std; {
template<class T> int Array1[ ]={1,4,6,2,6};
void GenericBubblesort(T
TempGenericArray[ ]) //template GenericBubbleSort(Array 1);
function1 //calling function template 1
{ GenericDisplay(Array1);
for(int i=0;i<5;i++) //calling function template2
{ char Array2[ ]=”sdfka‟;
for(int j=i+1;j<5;j++) GenericBubbleSort(Array2);
{ //calling function template1
If(TempGenericArray[ GenericDisplay(Array2);
i]<TempGenericArray[j]) //calling function template2
{ float Array3[
int temp=TempGenericArray[i]; ]={7.0,9.4,5.2,2.5,0.5};
GenericBubbleSort(Array3);
TempGenericArray[i]=TempGenericArray //calling function template1
[j]; GenericDisplay(Array3);
TempGenericArray[j]=temp; //calling function template2
}
} }
}
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 23
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

template<class T> Output:


void GenericDisplay(T 6 6 4 2 1
TempGenericArray[]) //template s k f d a
function2
{ 9.4 7 5.2 2.5 0.5
cout<<”\n”;
for(int i=0;i<5;i++)
{
cout<<TempGenericArray[i]<<”\t”;
}

Two Templates Functions Used:


 GenericBubbleSort
 GenericDisplay
1.2 Function Template with Multiple Arguments:
 It is possible to have templates with more than one argument.
 Other arguments can be generic or normal.
Program
# include<iostream> void main( )
# include<conio> {
using namespace std; int a =2,b=5;
template<class T> Max(a,b);
void Max(T x,T y) //calling template function
//template function float f1=3.4,f2=0.4;
{ Max(f1,f2);
if(x>y) //calling template function
cout<<x<<”is bigger\n”; char C1=‟A‟,C2=‟B‟;
else Max(C1,C2);
cout<<y<<”is bigger\n”; //calling template function
} char *ch1=”Rohit”,*ch2=”Mohit”;
Max(Ch1,Ch2);
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 24
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Output:
5 is bigger
3.4 is bigger
B is bigger
Mohit is bigger

1.3 Function Template with two generic Arguments


Simple Search program for searching an element in an array
# include<iostream> void main( )
# include<conio> {
using namespace std; int i;
template<class T> int Array1[ ]={10,33,34,12,45};
void GenericSearch(T GenericSearch(Array1, 12);
TempGenericArray[ ], T Ele //calling template fumction
ToBeSearched) char Array2[ ]=”asdef”;
//Template Function GenericSearch(Array2, f);
{ }
for (int i=0;i<5;i++) Output
{ The element 12 is at position 3
if(EleToBeSearched= The element f is at position 4
=TempGenericArray[i])
cout<<”\nThe
element”<<EleToBeSearched<<”is at
position”<<i;
}
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 25
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

1.4 Function Template with Non generic Parameters


# include <iostream> {
# include <conio> cout<<TempGenericArray[i]<<”\t”;
using namespace std; }
template<class T> }
void GenericBubblesort(T void main( )
TempGenericArray[ ],int size) //template {
function1 with non-generic arg int Array1[ ]={1,4,6,2,6};
{
for(int i=0;i<size-1;i++) GenericBubbleSort(Array 1,5);
{ //calling function template1
for(int j=i+1;j<size;j++) GenericDisplay(Array1,5);
{ //calling function template 2
If(TempGenericArray[ char Array2[ ]=”sdfka‟;
i]<TempGenericArray[j]) GenericBubbleSort(Array2,5);
{ //calling function template1
int temp=TempGenericArray[i]; GenericDisplay(Array2,5);
//calling function template2
TempGenericArray[i]=TempGenericArray[j float Array3[ ]={7.0,9.4,5.2,2.5,0.5};
]; GenericBubbleSort(Array3,5);
TempGenericArray[j]=temp; //calling function template1
} GenericDisplay(Array3,5);
} //calling function template2
} }
} Output:
template<class T> 6 6 4 2 1
void GenericDisplay(T s k f d a
TempGenericArray[],int size) //template
function2 with non-generic arg 9.4 7 5.2 2.5 0.5
{
cout<<”\n”;
for(int i=0;i<size ;i++)

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 26
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

1.5 Overloading Template Function


# include <iostream> void main( )
# include <conio> {
using namespace std; Print(10);
template<class T> //calling one argument template
void Print(T X) function
//one argument template function Print(‘c’);
{ cout<<”\n”;
cout<<x<<” “; Print(2,3);
} //calling two argument template
template<class T> function
void Print(T x,T y) Print(‘a’,’b’);
//two argument template function //calling two argument template
{ function
cout<<x<<” “<<y<<” “; }
} Print( ) is a Template
Two Versions of Generic Function:
Print (T x)
Print (T x, T y)

10. Explain about class template with an example.


Class Template
Definition:
“A generic class outlined by specification of a generic type using template keyword.
The actual class is defined later using this template”
Format:
template<class t>
Class classname
{
//…..
//class member specification with anonymous type T wherever
appropriate

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 27
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

};
Note:
A class created from a class template is called template class.

2.1 Friends of Class Template:


A friend of a class template can be one of the following:
1. Class template
2. Function template
3. Ordinary (non-template) function
4. Ordinary (non-template) class
5. A specialization of class template
6. A specialization of function template

2.2 The following program illustrates the concept of Class template:


Program: Stack
# include <iostream> ElementType pop( )
using namespace std; {
template<typename ElementType> if (stack pointer==0)
class stack cout<<"stack underflow,cannot
{ pop";
private: else
int stack pointer; {
ElementType stack array[10]; stack pointer--;
public: return stack array{stack
stack() pointer];
{ }
stack pointer=0; }
} };
void push (ElementType values) void main()
{ {
if (stack pointer==9) stack <int> mystack;
{ mystack.push(1);
cout<<"stack overflow! can't mystack.push(2);

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 28
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

insert!"; cout<<mystack.pop()<<"\n";
} cout<<mystack.pop()<<"\n";
else stack <char>yourstack;
{ mystack.push(„n‟);
stack array[stack mystack.push(„o);
pointer]=value; cout<<mystack.pop()<<"\n";
stack pointer ++; cout<<mystack.pop()<<"\n";
}
} }

2.3 Defining Functions of a Class Template outside the Class:


# include <iostream> template<typename ElementType>
using namespace std;
Element Type Stack<Element Type>::pop( )
template<typename ElementType>
class stack {
{ if (stack pointer==0)
private: cout<<"stack underflow,cannot
int stack pointer; pop";
ElementType stack array[10]; else
public: {
stack() stack pointer--;
{ return stack array{stack
stack pointer=0; pointer];
} }
void push (ElementType); }
void main()
ElementType pop( );
{
}; stack <int> mystack;
template<typename ElementType> mystack.push(1);
mystack.push(2);
void stack<Element Type>::push(ElementType
cout<<mystack.pop()<<"\n";

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 29
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

value) cout<<mystack.pop()<<"\n";
stack <char>yourstack;
{
mystack.push(„n‟);
if (stack pointer==9)
mystack.push(„o);
{
cout<<mystack.pop()<<"\n";
cout<<"stack overflow! can't insert!";
cout<<mystack.pop()<<"\n";
}
else
}
{
stack array[stack pointer]=value;
stack pointer ++;
}
}

2.4 Template Class with Multiple Generic Data Types


# include <iostream> void Sample<T1,T2>: :Print(T1 x,T2 y)
# include <conio> {
using namespace std; cout<<”\n x:”<<x;
template<class T1,class T2> cout<<”\n y:”<<y;
//template class with different
generic types }
class Sample void main( )
{ {
public: Sample<int,char>s1;
void Print(T1,T2); S1.Print(12,‟b‟);
}; Sample<char,char*>s2;
template<class T1,class T2> s2.Print(„c‟,”Rohit”);
//defining member function of
template class }

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 30
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Output
x:12
y:b
x:c
y:Rohit

2.5 Template Class with Non Generic Arguments


# include <iostream> void main( )
# include <conio> {
using namespace std; Sample<int, 3>s1;
template<class T,int no_of_time> s1.Print(5);
//template class with non type arg Sample<char, 5>s2;
class Sample s2.Print(„A‟);
{ }
public: Output
void Print(T x); 5 5 5 A A A A A
};
template<class T,int no_of_time>
//defining class template member
function
void Sample<T, no_of_time>: :Print(T
x)
{
for(int i=0;i< no_of_time;i++)
{
cout<<x<<”\t”;
}
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 31
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

2.6 Template Class using Default Arguments


# include <iostream> void main( )
# include <conio> {
using namespace std; Sample<int>s1;
template<class T=int, int //non generic argument is missing
no_of_time=3> s1.Print(5);
//template class with default Sample<char, 5>s2; //a new
arguments value to both arguments
class Sample s2.Print(„A‟);
{ Sample<>s3;
public: //both arguments are missing
void Print(T x); S3.Print(10);
}; }
template<class T,int no_of_time> Sample Output
//defining class template member 5 5 5 A A A A
function A 10 10 10
void Sample<T, no_of_time>: :Print(T x)
{
for(int i=0;i< no_of_time;i++)
{
cout<<x<<”\t”;
}
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 32
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

11. Explain the different forms of inheritance in detail. (Nov/Dec 2009)

Inheritance:

Definition:

 The mechanism of deriving a new class from an old one is called inheritance
(or) derivation.
 The new class is referred as base class and new one is called derived or sub-
class.

Base class:

 The class being extended in the process of inheritance is known as base


class.

Derived or sub-class:

 The extended class itself is known as the derived class.

Different forms of Inheritance:

 Single inheritance

 Multiple inheritance

 Hierarchical inheritance

 Multilevel inheritance

 Hybrid inheritance

 Multipath inheritance /Virtual base class

1. Single Inheritance

Definition:

 Single class is derived from a single base class. The derived class may inherit
all or partial properties of base class.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 33
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Syntax

class base class-name

//data members

//member functions

};

class derived-class-name: visibility-mode base-class-name

//data members

//member functions

};

Example

class A.

……………

……………

};

class B : public A

…………

…………

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 34
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program

//single.cpp

# include<iostream> void DisplayData( )


# include<conio> {
using namespace std;
Person::DisplayData( );
class Person //Base Class
//calling base class member function
{
cout<<”Roll no:<<Rollno<<endl;
private:
cout<<”Branch :<<Branch<<endl;
char *Name;
}
char Sex;
};
int Age;

public: void main( )

void ReadData( ) {

{ Student S1;

cout<<”Name :”; S1.ReadData( );

cin>>Name; //calling base class member function


cout<<”Sex: “; S1.DisplayData( );
cin>>Sex;
//calling base class member function
cout<<”Age :”;
}
cin>>Age;
Output:
}
Name : Rohit
void DisplayData( )
Sex :M
{
Age : 21
cout<<”Name :”<<Name<<endl;

cout<<”Sex :”<<Sex<<endl; Roll no: 1234

cout<<”Age:”<<Age<<endl; Branch : CSE

} Name : Rohit

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 35
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

}; Sex :M

class Student: public Person Age : 21

//Derived class and public derivation Roll no: 1234

{ Branch : CSE

private:

int Rollno;

char *Branch;

public:

void ReadData( )

Person::ReadData( );

//Calling base class member function

cout<< “Roll no : “;

cin>>Rollno;

cout<<”Branch :”;

cin>>Branch;

2. Multiple inheritances

 Refers to the act of derivation of a single class from several base classes.

A B

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 36
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Syntax

class Derived-class-name : visibility-mode Base-class-name1,visibility-mode


Base class-name2,…

Body of derived class

Example

class A

……………..

……………..

};

class B

……………..

…………….

};

class C : public A, public B

……………

……………

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 37
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program

# include<iostream> class Result: public InternalExam,


public ExternalExam
# include<conio>
{
using namespace std;
private:
class InternalExam
int Sub1Total,Sub2 Total;
{
public:
protected:
void ReadData( )
int Sub1Marks;
{
int Sub2Marks;
InternalExam::ReadData( );
public:
ExternalExam::ReadData();
void ReadData( )
}
{
void TotalMarks( )
cout<<”Marks scored in Subject1:”;
{
cin>>Sub1Marks;
Sub1Total=Internal Exam:
cout<<”Marks scored in Subject 2:”; :Sub1Marks+ExternalExam::Sub1Marks;
cin>>Sub2Marks; Sub2Total=Internal Exam::
} Sub1Marks+ExternalExam::Sub2Marks;

void DisplayData( ) }

{ void DisplayData( )

cout<<”\n Internal marks scored in {


Subject1:”<<Sub1Marks; InternalExam::DisplayData( );
cout<<”\n Internal marks scored in ExternalExam::DisplayData( );
Subject2:”<<Sub2Marks;
cout<<”\nSubject1
} Marks:”<<Sub1Total;
}; cout<<”\nSubject2
class ExternalExam Marks:”<<Sub2Total;

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 38
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

{ }

protected: };

int Sub1Marks; void main( )

int Sub2Marks; {

public: Result r;

void ReadData( ) r.ReadData( );

{ r.TotalMarks( );

cout<<”Marks scored in Subject1:”; r.DisplayData( );

cin>>Sub1Marks; }

cout<<”Marks scored in Subject 2:”; Output:

cin>> Sub2Marks; Marks Scored in Subject1: 18

} Marks Scored in Subject 2:20

void DisplayData( ) Marks Scored in Subject1: 78

{ Marks Scored in Subject 2:75

cout<<”\n External marks scored in Internal Marks scored in Subject1:18


Subject1:”<<Sub1Marks;
Internal Marks scored in Subject2:20
cout<<”\n External marks scored
in Subject2:”<<Sub2Marks; External Marks scored in Subject1:78

} External Marks scored in Subject1:75

}; Subject1 Marks: 96

Subject2 Marks: 95

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 39
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

3. Multilevel inheritance

 The mechanism of deriving a class from another derived class is known as


multilevel inheritance.
A

Syntax:

class Base-class-name

Body of Base class

};

class Derived-class-name1:visibility-mode Base-class-name

Body of derived class1;

};

class Derived –class-name2:Visibility-mode Derived-class-name1

Body of derived class2;

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 40
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program

//Multilevel.cpp class Exam: public Student


//derived class
# include<iostream>
{
# include<conio>
private:
using namespace std;
int Sub1Marks;
class Person //Base Class
int Sub2Marks;
{
public:
private:
void ReadData( )
char *Name;
{
char Sex;
Student: : ReadData( );
int Age;
cout<<”Marks scored in
public: subject1:”<<endl;
void ReadData( ) cin>>”Sub1Marks;
{ cout<<”Marks scored in
subject2:”<<endl;
cout<<”Name :”;
cin>>”Sub2Marks;
cin>>Name;
}
cout<<”Sex: “;
void DisplayData( )
cin>>Sex;
{
cout<<”Age :”;
Student: :DisplayData( )
cin>>Age;
cout<<”Marks scored in
}
subject1:”<<endl;
void DisplayData( )
cou<<”Sub1Marks;
{
cout<<”Marks scored in
cout<<”Name :”<<Name<<endl; subject2:”<<endl;

cout<<”Sex :”<<Sex<<endl; cout<<”Sub2Marks;

cout<<”Age:”<<Age<<endl; cout<<”Total marks


Scored:”<<Sub1Marks+Sub2Marks;
}
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 41
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

}; };

class Student: public Person void main( )


//Derived class and public
derivation {

{ Exam e;

private: e.ReadData( );

int Rollno; e.DisplayData( );

char *Branch; }

public: Output

void ReadData( ) Name : Rohit

{ Sex :M

Person::ReadData( ); Age : 21
//Calling base class member
Roll no: 1234
function
Branch : CSE
cout<< “Roll no : “;
Marks Scored in Subject1:75
cin>>Rollno;
Marks Scored in Subject2:78
cout<<”Branch :”;
Name : Rohit
cin>>Branch;
Sex :M
}
Age : 21
void DisplayData( )
Roll no: 1234
{
Branch : CSE
Person::DisplayData( );
//calling base class member Marks Scored in Subject1:75
function
Marks Scored in Subject2:78
cout<<”Roll no:<<Rollno<<endl;
Total Marks scored: 153
cout<<”Branch :<<Branch<<endl;

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 42
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

4. Hierarchical inheritance

B C D

The traits of one class may be inherited by more than one class.

Syntax

class Base-class-name

-----------

};

class Derived-class-name1:visibility-mode Base-class-name

-----------

};

class Derived-class-nameN:visibility-mode Base-class-name

………..

};

5. Hybrid inheritance

 Derivation of a class involving more than one form of inheritance is known


as hybrid inheritance.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 43
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

B C

Syntax:

class Base-class-name1

………….

};

class Derived-class-name1:visibility-mode Base-class-name

…………

};

class Base-class-name2

…………

};

class Derived-class-name2:visibility-mode Derived-class-name1,visibility-mode


Base-class-name2

………….

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 44
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

6. Multipath inheritance /Virtual base class

 Derivation of a class from other derived classes, which are derived from the
same base class, is called multipath inheritance.

B C

D
Example:

class A class C: virtual public A

{ {

………. ……….

}; };

class B: virtual public A class D : public B, public C

{ {

………. ………

}; };

Advantages of Using Inheritance

 The need of extending functionality of an existing class.

 To model a real world hierarchy in our program it is better to have


inheritance to our program.

 We have multiple classes with some attributes common to them. We would


like to avoid problems of inconsistency between the common attributes

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 45
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

12. Write a C++ program for virtual base class (Multipath Inheritance).

Multipath inheritance /Virtual base class

Definition:

 Derivation of a class from other derived classes, which are derived from the
same base class, is called multipath inheritance.

Grand
Parent

Parent1 Parent2
B C

Child

D
Example:

class A class C: virtual public A //Parent2


//Grand Parent
{
{
……….
……….
};
};
class D : public B, public C
class B: virtual public A //Parent1 //Child

{ {

………. ………

}; };

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 46
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program: //Virtual baseclass.cpp

# include<iostream> class D :public B, public C

#include<conio.h> {

using namespace std; public:

class A int s;

{ };

public: void main( )

int p; {

}; D obj;

class B: virtual public A Obj.p=10;


//virtual base class
Obj.q=10;
{
Obj.r=10;
public:
Obj.s=10;
int q;
}
};

class C : virtual public A


//virtual base class

public:

int r;

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 47
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

13. Discuss in detail about various derivations of inheritance (Public, Private


and Protected).

Different Type of Derivation:

The three possible styles of derivation are

 Public Derivation

 Private Derivation

 Protected Derivation

1. Public derivation or public inheritance:

 Inheriting class in a way that public and protected members of the base
class retain their status in the derived class

Derivation using public access modifier:

Syntax:

Class base

body of the base

};

Class derived: public base

body of the derived

};

The members of the base class are called the derivation known as public
derivation and consist of the following:

1. The public members of the base class are treated as public members of the
derived class.

2. Private members are not inherited.

3. If we have defined some members as protected in the base class, they are
available as protected in the derived class.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 48
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

PROGRAM:

# include<iostream.h> void main( )


# include<conio.h> {
using namespace std; D objd;
class B objd.a=10; // NOT
{ OK
private: objd.x=10; // NOT
int a; OK
public: objd.b=10;
int b; objd.y=10;
void SetB(int value) objd.SetB(20);
{ objd.SetD(30);
a=value; }
}
};
class D : public B
{
private:
int x;
public:
int y;
void SetD(int value)
{
x=value;
}
};

2. Private derivation or private inheritance:

 Inheriting class in a way that a public and protected member of the base
class becomes private members of the derived class.

Derivation using private access modifier: Syntax:

Class base
{
body of the base
};
Class derived: private base
{
body of the derived
};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 49
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

The members of the base class are called the derivation known as private
derivation and consist of the following:

1. Public members of the base class are treated as private members of the
derived class.

2. Like public derivation, private members of base class are inherited and thus
not available to derived.

3. If we have defined some members as protected in the base class, they are
available as private in the derived class.

PROGRAM:

# include<iostream.h> void main( )


# include<conio.h> {
using namespace std; D objd;
class B objd.a=10; // Not Ok
{ objd.x=10; // Not Ok
private: objd.b=10; // Not Ok
int a; objd.y=10;
public: objd.SetB(20); // Not Ok
int b; objd.SetD(30);
void SetB(int value) }
{
a=value;
}
};
class D : private B
{
private:
int x;
public:
int y;
void SetD(int value)
{
x=value;
b=value;
SetB(20);
//defining base class member
function
}
};

3. Protected derivation or protected inheritance:

 Inheriting class in a way that a public and protected member of the base
class becomes protected members of the derived class.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 50
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Derivation using protected access modifier:

Syntax:

Class base
{
body of the base
};
Class derived: protected base
{
body of the derived
};

The derivation is called protected derivation. The base class elements are
treated as follows:

1. The public members of the base class are treated as protected members of
the derived class.

2. Private members are not inherited.

3. If we have some members as protected in the base class, they are available
as protected in the derived class.

PROGRAM:

# include<iostream.h> void SetD(int value)


# include<conio.h> {
using namespace std; x=value;
class B b=value;
{ y=value;
protected: SetB(20);
int a; }
public: };
int b; void main( )
void SetB(int value) {
{ D objd;
a=value; objd.a=10; // Not Ok
} objd.x=10; // Not Ok
}; objd.b=10; // Not Ok
class D : protected B objd.y=10; // Not Ok
{ objd.SetB(20); // Not Ok
private: objd.SetD(30);
int x; }
public:
int y;

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 51
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

14. Write a C++ program handling the following details for students and staff
using inheritance. Student details: Name, address and percentage of marks,
Staff details : Name, address and salary. Create appropriate base and derived
classes. Input the details and output them (Nov/Dec 2010)

#include<iostream> class staff : public Student


#include<conio> //Derived class and public derivation
using namespace std; {
class Student private:
//Base class int Salary;
{ public:
private: void ReadData( )
char *Name; {
char *Address; Student: :ReadData( );
int marks; //Calling base class member function
public: cout<<”Salary:”;
void ReadData( ) cin>>Salary;
{ }
cout<<”Name:”; void DisplayData( )
cin>>Name; {
cout<<”Address:”; Person::DisplayData( );
cin>>Address; //Calling base class member function
cout<<”marks:”;
cin>>marks; cout<<”Salary:”<<salary<<endl;
} }
void DisplayData( ) };
{ void main( )
cout<<”Name:”<<Name<<endl; {
cout<<”Address:”<<Address<<endl; Staff S1;
cout<<”marks:”<<marks<<endl; S1.ReadData( );
} //Calling base class member function
}; S1.DisplayData( );
//Calling base class member function
}

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 52
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

15. Explain in detail about virtual function.(or) What are types of


polymorphism? Write about this pointer with example program? (or) Discuss
in detail about Run Time Polymorphism

Polymorphism

 “Polymorphism is the property of the same object to behave differently in


different contexts given the same message”

Two types of polymorphism

1. Compile time polymorphism

2. Run time polymorphism

Polymorphism

Runtime
Compile Time

Function Operator Virtual


Overloading Overloading Functions

Overview

 Introduction (Compile Time polymorphism and Runtime Polymorphism)

 Pointer object

 This pointer

 Compatibility of derived and base class pointers

 Virtual Functions

 Static vs Dynamic Binding

 Default Arguments to Virtual functions

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 53
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

 Static invocation of Virtual function

 Advantages of using virtual functions

 Use of Virtual Functions

 Pure Virtual Functions

1. Introduction

Compile Time Polymorphism

 Achieved by function overloading and operator overloading

Function overloading:

 A single function name can be used for various purposes (with different
arguments)

Operator overloading:

 Single operator is used to achieve multiple operations (with different type of


operands)

Runtime polymorphism

 Run time polymorphism is achieved by virtual functions.

 Resolving function call at run time is known as runtime or late or dynamic


binding.

 Runtime polymorphism allows selecting the suitable function at run time.

2. Pointer object

 Pointer object is a variable containing an address of an object which is


similar to pointer variable.

 Use & operator to get the address of an object.

Advantages

 Pointer object is used to achieve a run time polymorphism.

 It is a polymorphic object to access member functions of different classes.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 54
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

3. This Pointer

Definition

The name “this” is a keyword. The pointer this allows to access the current object
only.‟ This‟ pointer is used within a method to access an object member. It is also
used to return the address of the current object.

Program

#include<iostream> A disp( )
#include<conio> {
using namespace std; return *this;
class A //returns the address of an object
{ }
private: };
int x; void main( )
public: {
A( ) {} A(10);
A(int a) A a1,a2;
{ a2=a1.Disp( );
this->x=a; }
//accessing data member
}

4. Compatibility of derived and base class pointers

#include <iostream> int main()


using namespace std; {
class Base Base *p = new Derived;
{ // get rid of parens
public: p->runme();
virtual void runme() { return 0;
cout << "Base" << endl; } }
};

class Derived : public Base


{
public:
virtual void runme() {
cout << "Derived" << endl; }
};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 55
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

VIRTUAL FUNCTIONS:

Definition:

“A function defined with virtual keyword in the base class is known as


virtual function. Compiler will decide the exact class pointed to, by the base class
pointer and call the respective function of that class if the function is defined as
virtual”.

Explanation:

 The class has an additional storage requirement when atleast one virtual
function is defined inside.

 A table is created additionally to store pointers to all virtual functions


available to all the objects of the class.

 This table is known as the virtual table.

Virtual table:

“A table consisting of pointers to all virtual functions of class, every class


with atleast one virtual function will have one copy of virtual table”.

Note:

The virtual table may also be created when we use run time type information [
RTTI ].

SYNTACTICAL CONSTRAINTS ON USE OF VIRTUAL FUNCTION:

 Functions name must be preceded by virtual keyword in the base class.

 Virtual constructors are not possible. Constructing a derived class object


needs specific construction of the base class subobject within..

 The function in the derived class must have same name as of the virtual
function defined in the base class and the same prototype.

 The function in the derived class need not be preceded by the virtual
keyword.

 The virtual function must be defined in the base class, it may have an empty
body.

 The virtual functions are members of the classes of the hierarchy.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 56
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program:

#include<iostream> Void main()


#include<conio> {
Using namespace std; Shape *pts, s;
class shape Circle c;
{ Ptrs=&s;
public: Ptrs->draw();
virtual void draw() Ptrs=&c;
{ Ptrs->draw();
cout<<”shape is drawn”; }
} Output:
}; Shape is drawn
Class circle: public shape Circle drawn
{
Public:
Void draw()
{
Cout<<”circle is drawn”;
}
};

Virtual Destructors

The issue of more unreferenced memory blocks is solved by virtual destructors.

Syntax

class shape

public:

virtual ~shape( ){………} //virtual destructors

};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 57
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Rules for virtual function:

 Functions name must be proceeded by virtual keyword in the base class.

 Virtual constructors are not possible. Constructing a derived class object


needs specific construction of the base class sub object within.

 The function in the derived class must have same name as of the virtual
function defined in the base class and the same prototype.

 The function in the derived class need not be preceded by the virtual
keyword.

 The virtual function must be defined in the base class, it may have an
empty body.

 The virtual functions are members of the classes of the hierarchy.

Program

//Virtual Functions.cpp void main()


#include<iostream.h> {
#include<conio.h> Shape *ptr,s;
using namespace std; Circle c;
class Shape
{ ptrs=&s;
public: ptrs->Draw( );
virtual void Draw() //calling base class draw
{ function
cout<<"\n Shape is drawn:";
} ptrs=&c;
}; ptrs->Draw( );
//calling derived class draw
class Circle: public shape function
{
public: }
void Draw( ) Output:
{ Shape is drawn
cout<<"\n Circle is drawn:"; Circle is drawn
}
};

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 58
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Static vs Dynamic Binding

Static Binding Dynamic Binding

Static binding is dynamic binding refers


method resolution at to method resolution
compile time at run time

Default Arguments to Virtual functions

 Default arguments to virtual function works, when you supply explicit value
to replace the default value

Program

//Default Virtual Functions.cpp void main()


#include<iostream.h> {
#include<conio.h> Shape *ptr,s;
using namespace std; Circle c;
class Shape
{ ptrs=&s;
public: ptrs->Draw( 10);
virtual void Draw (int Size=100) //calling base class draw function
{
cout<<Size; ptrs=&c;
} ptrs->Draw( 20);
}; //calling derived class draw
class Circle: public shape function
{ }
public: Output:
void Draw( int size=200)
{
cout<<size;
}
};

Static invocation of Virtual function

 It is possible to call virtual function using an object of the class or using a


scope resolution operator. In that case the virtual function is statically
linked. This is known as static invocation of the virtual function.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 59
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program:

#include<iostream> void main( )


#include<conio> {
using namespace std; One *ptr1=new One();
class One ptr1->One: :Show( );
{
public: //calls the base class virtual function
virtual void show ( ) Two *ptr2=new Two( );
{ ptr2->Two: : Show( );
cout<<”One”; // calls the derived class virtual function
} }
};
class Two: public One output:
{ ptr1->One: :Show( );
public: ptr2->Two: :Show( );
void show( ) are known as statically invoked calls to
{ virtual functions
cout<<”Two”;
}
};

Advantages of using virtual functions

 Provides more flexibility


 Eg: Generation of a cartoon movie
 Latest News Telecast

Use of Virtual Functions

 Virtual functions will prove to be another tool for software reuse.

 Virtual functions supports late/dynamic binding

Pure Virtual Functions

 C++ allows you to create a special kind of virtual function called a pure
virtual function (or abstract function) that has no body at all! A pure
virtual function simply acts as a placeholder that is meant to be redefined by
derived classes.

Syntax

virtual void display ( ) =0;

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 60
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Program

#include<iostream.h> void dev :: display( )


#include<conio.h> {
class base cout<<”Name is :”<<name<<endl;
{ cout<<” Roll no is :”<<roll <<endl;
private: }
int x;
float y; void main( )
public : {
virtual void getdata( ); base * ptr;
virtual void display( ); dev obj;
}; clrscr( );
class dev : public base ptr = &obj;
{ ptr -> getdata( );
private: ptr -> display( );
int roll; getch( );
char name[20]; }
public :
void getdata( ); OUTPUT
void display( ); Enter the roll no of the student: 111
}; Enter the name of the student : Kapil Dev
void base :: getdata( ) { } Name is : Kapil Dev
void base :: display( ) { } Roll no is : 111

void dev :: getdata( )


{
cout<<” Enter Roll of the Student “;
cin>> roll;
cout<<” Enter name of the student”;
cin>>name;
}

16. Write a short note on abstract class?

ABSTRACT CLASS:

Definition:

 An abstract class is, conceptually, a class that cannot be instantiated and is


usually implemented as a class that has one or more pure virtual (abstract)
functions.
 A pure virtual function is one which must be overridden by any concrete
(i.e., non-abstract) derived class. This is indicated in the declaration with the
syntax " = 0" in the member function's declaration.

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 61
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Example

class AbstractClass Class File // abstract class serves as


interface
{
{
public:

virtual void AbstractMemberFunction() Public:


= 0;
Int virtual open()=0; // pure virtual
// Pure virtual function makes
Int virtual close()=0;
// this class Abstract class.
};
virtual void
NonAbstractMemberFunction1();

// Virtual function.

void NonAbstractMemberFunction2();

};

17. Write suitable C++ coding for Composite Runtime Polymorphism

Composite object or Container object

 “Object which includes other objects as data members.”

Introduction

 Composite objects are different from derived objects

 They contain the objects of other classes as data members

 They do not have inheritance relationship with the contained objects.

 Contained objects are said to have a part-of relationship with the container
objects

Example:

class Engine
{
………
};
Class Car

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 62
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

{
…….
Engine e; //composition of object of the class engine
};

Program:

#include<iostream> class Two


#include<conio> //Composite object
using namespace std; {
class one int b;
//embedded object One a;
{ //object of class One is embedded here
int a; public:
public: Two(One t, int y)
One( ){ } {
One(int X) a=t;
{ b=y;
a=x; }
} };
}; void main( )
{
Two(One(10),20);
//calling the constructor of the composite
object
}

Comparison of Inheritance Vs Composition

Inheritance Composition
Inheritance is a derivation of Containing an object of class
properties of existing class into another class
into a new class
The relationship between the “has-a” or “part-of”
classes is “is-a”relationship. relationship
E.g Vehicle Scooter
E.g Face[Nose]

Inherited members must To execute the constructors


execute their constructors of the contained objects in
outside the constructor body the container .class
of derived class using constructor use MIL
member initialization
list.(MIL)

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 63
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

ANNA UNIVERSITY QUESTIONS

PART – A

1. What is friend function? [Nov/Dec 2011]


Refer-Q-No: 01
2. What is virtual base class? [Nov/Dec 2011]
Refer-Q-No: 28
3. List the operators that cannot be overloaded. [May/Jun 2012]
Refer-Q-No: 9
4. What are pure virtual functions? Where are they used? [May/Jun 2012]
Refer-Q-No: 5
5. Why can’t friend function be used to overload assignment operator?
[Nov/Dec 2012]
Refer-Q-No: 15
6. What is a virtual class? Why is it used in C++? [Nov/Dec 2012]
Refer-Q-No:28
7. Compare overloading and overriding. [May/Jun 2013]
Refer-Q-No: 7
8. What is the size of a class having one or more virtual functions?
[May/Jun 2013]
Refer-Q-No: 4
9. What is the use of operator overloading? [Nov/Dec 2013]
Refer-Q-No: 8
10. What is friend class? [Nov/Dec 2013]
Refer-Q-No: 1

PART - B

1. Create classes that contain one data member. Overload all the four
arithmetic operators so that they operate on the objects of that class.
[Nov/Dec 2011]
Refer-Q-No: 1
2. Describe the syntax of the different forms of inheritance in
C++.[Nov/Dec 2011]
Refer-Q-No: 11
3. What are virtual functions? Explain with a suitable program. [Nov/Dec
2011]
Refer-Q-No: 15
4. What is dynamic binding? How is it achieved? [Nov/Dec 2011]
Refer-Q-No: 15
5. Write a C++ program to implement C= A+B, C=A-B and C=A*B where A,B
and C are objects containing a int value (vector). [May/Jun 2012]
Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 64
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-II)

Refer-Q-No: 1
6. Explain run time polymorphism with example program. [May/Jun 2012]
Refer-Q-No: 15
7. Explain about the implementation of runtime polymorphism in C++
with an example. [Nov/Dec 2012]
Refer-Q-No: 15
8. Explain the types of inheritance with example. [Nov/Dec 2012]
Refer-Q-No: 11
9. Explain the usage of template in C++.[Nov/Dec 2012]
Refer-Q-No: 9 & 10
10. Explain how left shift and right shift operator are overloaded with an
example. [Nov/Dec 2012]
Refer-Q-No: 4
11. Write a C++ program using operator overloading to add two time values
in the format HH:MM:SS to the resulting time along with rounding off
when 24 hours is reached. A time class is created and operator + is
overloaded to add the two time class objects. [May/Jun 2013]
Refer-Q-No: 6
12. Explain in detail about friend function in C++ with example. [May/Jun
2013]
Refer-Q-No: 3 and 2 mark Refer_Q-No:2
11. What is multiple inheritances? Discuss the syntax and rules of
multiple inheritances in C++. How can you pass parameters to the
constructors of base classes in multiple inheritances? Explain with
suitable example. [May/Jun 2013]
Refer-Q-No: 13
12. What is the difference between a virtual function and a pure virtual
function? Give example of each. [May/Jun 2013]
Refer-Q-No: 15
13. Explain friend function with an example. [Nov/Dec 2013]
Refer-Q-No: 3
14. Write a C++ program to concatenate two strings using + operator
overloading. [Nov/Dec 2013]
Refer-Q-No: 3
15. What is inheritance? List out the advantages of inheritance [Nov/Dec
2013]
Refer-Q-No: 11
16. Write a C++ program to implement hierarchical inheritance. [Nov/Dec
2013]
Refer-Q-No: 12

Prepared By
S.Amutha AP/IT,
Mathivanan AP/IT. 65

You might also like