Sie sind auf Seite 1von 207

DEPARTMENT OF INFORMATION TECHNOLOGY

CS6301 PROGRAMMING AND DATASTRUCTURES II

LECTURE NOTES

1

www.cseitquestions.in

UNIT I

OBJECT ORIENTED PROGRAMMING FUNDAMENTALS

C++ Programming features - Data Abstraction - Encapsulation - class - object -

constructors static members constant members member functions pointers

references - Role of this pointer Storage classes function as arguments.

1.1 C++ PROGRAMMING FEATURES:

1. The C++ programming language is based on the C language.

2. Although C++ is a descendant of the C language, the two languages are not always compatible.

3. In C++, you can develop new data types that contain functional descriptions (member functions) as well as data representations. These new data types are called classes.

4. The work of developing such classes is known as data abstraction. You can work with

a combination of classes from established class libraries, develop your own classes, or

derive new classes from existing classes by adding data descriptions and functions.

5. New classes can contain (inherit) properties from one or more classes. The classes

describe the data types and functions available, but they can hide (encapsulate) the

implementation details from the client programs.

6.

You can define a series of functions with different argument types that all use the same function name. This is called function overloading. A function can have the same name and argument types in base and derived classes.

7. Declaring a class member function in a base class allows you to override its implementation in a derived class. If you use virtual functions, class-dependent behavior may be determined at run time. This ability to select functions at run time, depending on data types, is called polymorphism.

8. You can redefine the meaning of the basic language operators so that they can perform operations on user-defined classes (new data types), in addition to operations on system-defined data types, such as int, char, and float. Adding properties to operators for new data types is called operator overloading.

9. The C++ language provides templates and several keywords not found in the C language. Other features include try-catch-throw exception handling, stricter type checking and more versatile access to data and functions compared to the C language.

2

www.cseitquestions.in

1.2 DATA ABSTRACTION:

Data abstraction refers to, providing only essential information to the outside world

and hiding their background details, i.e., to represent the needed information in

program without presenting the details.

Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.

 finally displays them on the screen.   changer, and volume control without having
finally displays them on the screen. 
changer, and volume control without having zero knowledge of its internals. 
actually knowing how class has been implemented internally. 
#include <iostream.h>
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}

Let's take one real life example of a TV, which you can turn on and off, change the

channel, adjust the volume, and add external components such as speakers, VCRs,

and DVD players, BUT you do not know its internal details, that is, you do not know

how it receives signals over the air or through a cable, how it translates them, and

Thus, we can say a television clearly separates its internal implementation from its

external interface and you can play with its interfaces like the power button, channel

Now, if we talk in terms of C++ Programming, C++ classes provides great level of

data abstraction. They provide sufficient public methods to the outside world to play

with the functionality of the object and to manipulate object data, i.e., state without

In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class ostream to stream data to standard output like this:

Here, you don't need to understand how cout displays the text on the user's screen.

You need to only know the public interface and the underlying implementation of

cout is free to change.

3

www.cseitquestions.in

Access Labels Enforce Abstraction:

In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels:

Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members.

Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type.

hide the implementation from code that uses the type.  There are no restrictions on how

There are no restrictions on how often an access label may appear. Each access label

specifies the access level of the succeeding member definitions. The specified access level remains in effect until the next access label is encountered or the closing right

brace of the class body is seen.  Data abstraction provides two important advantages: 
brace of the class body is seen.
Data abstraction provides two important advantages: 
be broken. 

Benefits of Data Abstraction:

Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.

The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is

free to make changes in the data. If the implementation changes, only the class code

needs to be examined to see what affect the change may have. If data are public, then

any function that directly accesses the data members of the old representation might

Data Abstraction Example:

Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example:

#include <iostream.h> using namespace std;

class Adder

{

public:

4

www.cseitquestions.in

// constructor Adder(int i = 0)

{

}

total = i;

// interface to outside world void addNum(int number)

{ total += number; } // interface to outside world int getTotal() { return total;
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside
world int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;

}

When the above code is compiled and executed, it produces the following result: Total 60

Above class adds numbers together, and returns the sum. The public members

addNum and getTotal are the interfaces to the outside world and a user needs to

know them to use the class. The private member total is something that the user

doesn't need to know about, but is needed for the class to operate properly.

5

www.cseitquestions.in

1.3 DATA ENCAPSULATION:

Data encapsulation is a mechanism of bundling the data, and the functions that use

them and data abstraction is a mechanism of exposing only the interfaces and hiding

the implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of

user-defined types, called classes. We already have studied that a class can contain private, protected and public members. By default, all items defined in a class are

private. For example: class Box { public: double getVolume(void) { return length * breadth *
private.
For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your
program. This is one way encapsulation is achieved. 
To make parts of a class public (i.e., accessible to other parts of your program), you

must declare them after the public keyword. All variables or functions defined after

the public specifier are accessible by all other functions in your program.

Making one class a friend of another exposes the implementation details and reduces

encapsulation. The ideal is to keep as many of the details of each class hidden from all

other classes as possible.

6

www.cseitquestions.in

Data Encapsulation Example:

Any C++ program where you implement a class with public and private members is an example of data encapsulation and data abstraction. Consider the following example:

#include <iostream.h> #include<conio.h> class Adder

{ public: // constructor Adder(int i = 0) { total = i; } // interface
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside
world int total;

};

int main( )

{

Adder a;

a.addNum(10);

a.addNum(20);

a.addNum(30);

7

www.cseitquestions.in

cout << "Total " ;

cout<< a.getTotal();

cout <<endl;

return 0;

}

When the above code is compiled and executed, it produces the following result: Total 60

and executed, it produces the following result: Total 60 Above class adds numbers together, and returns

Above class adds numbers together, and returns the sum. The public member‟s addNum and getTotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that is hidden from the outside world,

total is something that is hidden from the outside world, but is needed for the class

but is needed for the class to operate properly.

Designing Strategy:

Most of us have learned through bitter experience to make class members private by default unless we really need to expose them. That's just good encapsulation.

This wisdom is applied most frequently to data members, but it applies equally to all

frequently to data members, but it applies equally to all 1. Data Member 1.Public members, including
1. Data Member 1.Public
1. Data Member
1.Public

members, including virtual functions.

1.4 CLASS:

In oop, class is a user defined data type that can hold data and their associated functions into single unit.

The class members are divided into two types:

2. Function Member In class there are certain privilege for accessing both data and function members. They are said to be access specifiers.

It is divided into three categories. They are,

2.private

3.Protected

By default the data members are private. So the private members of a class are not

accessible from outside the class. If the data members are specified as public then the

members of a class can be accessible from inside and outside of the class.

8

www.cseitquestions.in

Syntax of a class

class class_name { Access Specifier: Data Members Access Specifier: Function Members }; Data Members Function
class class_name
{
Access Specifier:
Data Members
Access Specifier:
Function Members
};
Data Members
Function Members

Example:

Consider an example of class class student

{

public:

int rollno,age;

char *name;

void getdetail()

{

Cin>>rollno>>age;

Cin>>name;

}

void printdetail()

{

Cout<<rollno<<age;

Cout<<name;

}

};

In this example a class named student with data members such rollno, age and name

and with function members getdetail() and printdetail() is defined within the class.The access

specifiers of this class is public.

9

www.cseitquestions.in

Function Definition outside the Class

The function members which are declared inside the class can be defined outside of the class using Scope Resolution Operator ::

Syntax for Defining the Function outside the Class:

Return Type class_name::function_name() { Function Body } Return type specifies the type of a function.
Return Type class_name::function_name()
{
Function Body
}
Return type specifies the type of a function. Class name specifies the name of a class
in which the function belongs. The operator:: denotes scope resolution operator. Function
name specifies the name of a function.
Example:
class student
{
public:
int rollno,age;
char *name; void
getdetail(); void
printdetail(); };
void student::getdetail()
{
Cin>>rollno>>age;
Cin>>name;

}

void student::printdetail()

{

Cout<<rollno<<age;

Cout<<name;

}

10

www.cseitquestions.in

1.5 OBJECTS:

Objects are the variables of user defined data type called class. Once a Class has been

created we can declare any number of variables belongs to that class. In the above example

class student we can declare any number of variables of class student in the main function.

Using objects we can access any public members of a class using Dot Operator.

For accessing Data Members and assigning value:

class Name s1,s2,s3 are objects(variables) of class Student Object s1 assigns the value for the
class Name
s1,s2,s3 are objects(variables) of class Student
Object s1 assigns the value for the data member rollno=28
Object s1 access (call) the function member
printdetail () of student class

object_name.data_member=value;

For accessing Function Members:

Object_name.function_name();

Syntax:

Class_Name object1, object2, object3…….object n;

void main ()

{

student s1, s2,s3;

s1.rollno=28;

s1.getdetail (); Object s1 access (call) the function member getdetail () of student class

s1.printdetail ();

}

Memory Requirement for Objects and Class:

Once the object is created memory is allocated for the data members of a class and not

for its function Members‟ .So each object holds the total memory size of the data members.

For example in the class student the object s1 holds the memory size of 5 bytes. Char I byte,

int 2 bytes.

Once the class is created only single copy of function member is maintained which is common for all the objects.

11

www.cseitquestions.in

Class student Function Members: Void getdetail() Void printdetail() Object s1: Object s2: Object s3: Data
Class student
Function Members:
Void getdetail()
Void printdetail()
Object s1:
Object s2:
Object s3:
Data Member Name
Data Member Name
Data Member Name
Data Member Rollno
Data Member Rollno
Data Member Rollno
Data Member age
Data Member age
Data Member age
1.6 CONSTRUCTOR:
The main use of constructors is to initialize objects. The function of initialization is
automatically carried out by the use of a special member function called a constructor.
General Syntax of Constructor
A constructor is a special member function that takes the same name as the class
name. The default constructor for a class X has the form
X::X()
In the above example, the arguments are optional. The constructor is automatically
named when an object is created. A constructor is named whenever an object is defined or
dynamically allocated using the “new” operator.
There are several forms in which a constructor can take its shape namely:

Default Constructor:

This constructor has no arguments in it. The default Constructor is also called as the no argument constructor.

For example:

class Exforsys

{

12

www.cseitquestions.in

private:

int a,b;

public:

Exforsys();

};

Exforsys :: Exforsys() { a=0; b=0; } Parameterized Constructor: A default constructor does not have
Exforsys :: Exforsys()
{
a=0;
b=0;
}
Parameterized Constructor:
A default constructor does not have any parameter, but if you need, a constructor
can have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example:
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor Line::Line( double len)

{

cout << "Object is being created, length = " << len << endl; length = len;

13

www.cseitquestions.in

}

void Line::setLength( double len )

{

length = len;

}

double Line::getLength( void )

{

return length; } // Main function for the program int main( ) { Line line(10.0);
return length;
}
// Main function for the
program int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6

Copy constructor:

This constructor takes one argument, also called one argument constructor. The main

use of copy constructor is to initialize the objects while in creation, also used to copy an

object. The copy constructor allows the programmer to create a new object from an existing

one by initialization.

For example to invoke a copy constructor the programmer writes: Exforsys e3(e2);

or

14

www.cseitquestions.in

Exforsys e3=e2;

Both the above formats can be sued to invoke a copy constructor.

For Example:

#include <iostream> using namespace std; class Exforsys

{ private: int a; public: Exforsys() { } Exforsys(int w) { a=w; } Exforsys(Exforsys& e)
{
private:
int a;
public:
Exforsys()
{
}
Exforsys(int w)
{
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout << " Example of Copy Constructor";
}
void result()
{
cout<< a;
}

};

void main()

{

 

Exforsys e1(50);

Exforsys e3(e1);

cout<< "ne3=";e3.result();

}

15

www.cseitquestions.in

Destructors

Destructors are also special member functions used in C++ programming language.

Destructors have the opposite function of a constructor. The main use of destructors is to

release dynamic allocated memory.

Destructors are used to free memory, release resources and to perform other clean up.

Destructors are automatically named when an object is destroyed. Like constructors,

destructors also take the same name as that of the class name.

Some important points about destructors:  Destructors take the same name as the class name.
Some important points about destructors:
Destructors take the same name as the class name.
Like the constructor, the destructor must also be defined in the public. The destructor
must be a public member. 
The Destructor does not take any argument which means that destructors cannot be
overloaded. 
No return type is specified for destructors. 
class Exforsys
{
private:
public:
Exforsys()

General Syntax of Destructors

~ classname();

The above is the general syntax of a destructor. In the above, the symbol tilda ~ represents a destructor which precedes the name of the class.

For example:

{

}

~ Exforsys()

{

}

}

16

www.cseitquestions.in

1.7 STATIC MEMBERS:

The Static Data Member of a class is like a global variable. Once it is defined the static member will be initialized to zero. When the static member is declared inside the class it should be defined outside of the class. Static Data Member of a class will be common to all the objects which are declared in the class.

Syntax:

class stat { static int count; //static Data Member Declaration } int stat::count; //static Data
class stat
{
static int count; //static Data Member Declaration
}
int stat::count; //static Data member Defintion
Example Program:
#include<iostream.h>
#include<conio.h>
class count
{
public:
static int countt;
void dispcount()
{
countt++;
cout<<"Object\t"<<countt<<"\n";
}
};
int count::countt;
void main()
{
count c1,c2,c3,c4,c5;
clrscr();
c1.dispcount();
c2.dispcount();
c3.dispcount();

17

www.cseitquestions.in

c4.dispcount();

c5.dispcount();

getch();

}

In this example class count has a static data member countt.This program is used for

counting the number of objects which is declared in the class.So when an object c1 access the

Once the static data member is defined it is automatically initialized to zero.  Once
Once the static data member is defined it is automatically initialized to zero.
Once the object is declared as constant it cannot be modified by any function. 

will be incremented to 5.

Output:

Object 1

Object 2

Object 3

Object 4

Object 5

NOTE:

1.8 CONSTANT MEMBERS:

Constant Objects and Constant Functions

function dispcount() the static variable has the value 1.when s5 access the function the value

Initially the value for the data members is set by constructor during the object creation.

Constant objects can access only the constant member function .The constant function is read only function it cannot alter the value of object data members

Syntax- Constant Function & Constant objects

class class_name{

class_name(parameters)

{

18

www.cseitquestions.in

initialize the datamember with parameters;

}

return_type function_name() const

{

//Constant member function

//read only function

} }; void main() { const class_name object( parameter); //constant objects object.function(); //constant objects
}
};
void main()
{
const class_name object( parameter);
//constant objects
object.function(); //constant objects access Constant member function
}

Ex:

void printdetails() const

{

cout<<”Roll No is:”<<rollno; cout<<”Name is:”<<name; cout<<”Address is:”<<address;

rollno=10; / / the following line is erroneous

}

Mutable Data Members

In some cases if the static function need to modify the data member of an object, then the data member should be declared as mutable, so that static function can modify it.

mutable int rollno; void printdetails() const

{

rollno=10;

//it is allowed

}

19

www.cseitquestions.in

Example program for constant function and constant objects

#include<iostream.h>

#include<conio.h> class time

{

public:

int hour,minute,second;

//constant member function
//constant member function

time(int temphr,int tempmin,int tempsec)

{

hour=temphr;

minute=tempmin;

second=tempsec;

}

void disp() const

{

cout<<"Time is:"<<hour<<"Hour:\t"<<minute<<"Minutes:\t"<<second<<"Seconds:\n";

}

~time()

{

}

void get() const

{

cin>>hour>>minute>>second;

}

};

void main()

{

clrscr();

const time t1(8,55,50);

//Constant objects

t1.disp();

t1.get();

//cannot modify the datamembers of t1

t1.disp();

getch();

}

20

www.cseitquestions.in

Output

Time is:8Hour: 55Minutes:

5

50Seconds:

50

40

Time is:8Hour: 55Minutes:

50Seconds:
50Seconds:

Syntax

class stat

{

static return_type function_name()

{

Statement;

}

};

In this example, the object of this time class is set with the default value of 8 hour 55 minutes and 50 seconds and it is initialized with constructor. Since this object t1 is a n constant object it cannot be modified and it can access only the constant function in a class.

1.9 MEMBER FUNCTIONS:

1.9.1 Static Function

Static member functions have a class scope and they do not have access to the 'this' pointer of the class. When a member is declared as static, a static member of class, it has only one data for the entire class even though there are many objects created for the class. The main usage of static function is when the programmer wants to have a function which is accessible even when the class is not instantiated.

Calling Static Function in the main Function void main()

{

class_name::static function name();

}

21

www.cseitquestions.in

Example:

#include<iostream.h>

#include<conio.h> class count

{

public:

static int

#include<conio.h> class count { public: static int countt; count() { countt++;

countt; count()

{

countt++;

cout<<"Object\t"<<countt<<"\n";

}

static void statfun()

{

cout<<"Object\t"<<countt<<"\n";

}

};

int count::countt;

void main()

{

count c1,c2,c3,c4,c5; clrscr();

count::statfun();//calling the constructor using classname getch();//scope resolution operator and the static funtion name

}

Output:

Object 5

The programmer must note the following while using static member functions:

A static member function can only access static member data, static member functions

and data and functions outside the class. The programmer must take note not to use

static member function in the same manner as non-static member function, as non-

static member function can access all of the above including the static data member.

22

www.cseitquestions.in

 A non-static member function can be declared as virtual but care must be taken
A
non-static member function can be declared as virtual but care must be taken not to
declare a static member function as
The programmer must first understand the concept of static data while learning the
context of static functions. It is possible to declare a data member of a class as static
irrespective of it being a public or a private type in class definition. If a data is
declared as static, then the static data is created and initialized only once. Non-static
data members are created again and again. For each separate object of the class, the
static data is created and initialized only once. As in the concept of static data, all
objects of the class in static functions share the variables. This applies to all objects of 
the class.
A
non-static member function can be called only after instantiating the class as an
object. This is not the case with static member functions. A static member function
can be called, even when a class is not instantiated. 
A static member function cannot have access to the 'this' pointer of the class. 
We may either define a member function inside its class definition, or you may define
A member function that is defined inside its class member list is called an inline
An equivalent way to declare an inline member function is to either declare it in the

1.9.2 Inline member Function

it outside if you have already declared (but not defined) the member function in the class

definition.

member function. Member functions containing a few lines of code are usually declared

inline. In the above example, add() is an inline member function. If you define a member

function outside of its class definition, it must appear in a namespace scope enclosing the

class definition. You must also qualify the member function name using the scope resolution

(::) operator.

class with the inline keyword (or define the function outside of its class) or to define it

outside of the class declaration using the inline keyword.

1.10 POINTERS:

Every storage location of memory has an associated address. The address is a number

that grows sequentially. For every program placed in memory, each variable or function in

the program has an associated address.

23

www.cseitquestions.in

The address of operator:

The address of operator or Reference operator is denoted by the notation &. When the

user wants to get the address of a variable, then the reference operator & can be used. The

operator & is used to find the address associated with a variable.

The syntax of the reference operator is as follows:

&variablename - This means that the address of the variable name is achieved.

int exf=200; int test=300; cout << endl << &exf << endl << &test;
int exf=200;
int test=300;
cout << endl << &exf << endl << &test;

For Example

#include <iostream>

using namespace std;

void main()

{

}

The output of the above program could be one of the following, and at each run it differs slightly:

The &exf has the address associated with the integer variable exf and the &test has

the address associated with the integer variable test which are displayed using the cout

statement.

Using the understanding of address of operators, the discussion turns to the concept of pointers.

exforsys = 100;

test = exforsys;

x = &exforsys;

Using the above information, the assignment takes place as below:

24

www.cseitquestions.in

exforsys is an integer variable having the value of 100 stored in memory address location

exforsys is an integer variable having the value of 100 stored in memory address location

3501.

test = exforsys; x = &exforsys; To define pointer variable is as follows: datatype_of_ variable_pointedto*
test = exforsys;
x = &exforsys;
To define pointer variable is as follows:
datatype_of_ variable_pointedto* pointer_varaible;

When the variable exforsys is assigned to the variable test in the second statement:

The value of the variable exforsys 100 is copied to the variable test.

In the third statement, the address of the variable exforsys is denoted by reference operator &exforsys is assigned to the variable x as:

The address of the variable 3501 and not the contents of the variable exforsys is

copied into the variable x. The pointers concept fits in this statement. Pointers are the

variables that store the reference to another variable. Pointers are variables that store the

address of the variable that it is pointed by. Variable x is referred to as the pointer in the

above example.

The programmer must note that the address operator placed before a variable is not

the same as operator & placed after the variable. For example, &x is not same as x&.

Variable &x refers to address operator whereas x& refer to reference operator&. Pointer is a

variable that holds the address, also called pointer variable.

Defining Pointer Variables or Pointer:

For example:

char* ch;

This defines that ch is a pointer variable which points to char data type. int* i;

This defines that i is a pointer variable which points to int data type. float* f;

This defines that f is a pointer variable which points to float data type.

25

www.cseitquestions.in

1.11 REFERENCES:

A reference variable is an alias, that is, another name for an already existing variable.

Once a reference is initialized with a variable, either the variable name or the reference name

may be used to refer to the variable.

C++ References vs Pointers:

1. 2. reference is connected to a legitimate piece of storage. 3. 4. A reference
1.
2.
reference is connected to a legitimate piece of storage.
3.
4.
A reference must be initialized when it is created. Pointers can be initialized at any
time.
For example, suppose we have the following example:
int
i = 17;
We can declare reference variables for i as
follows.
int& r = i;

you can access the contents of the variable through either the original variable name or the

reference.

References are often confused with pointers but three major differences between references and pointers are:

You cannot have NULL references. You must always be able to assume that a

Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.

Creating References in C++:

Think of a variable name as a label attached to the variable's location in memory. You

can then think of a reference as a second label attached to that memory location. Therefore,

Read the & in these declarations as reference. Thus, read the first declaration as "r is

an integer reference initialized to i" and read the second declaration as "s is a double

reference initialized to d.". Following example makes use of references on int and double:

#include <iostream.h> int main ()

{

// declare simple variables int i;

26

www.cseitquestions.in

double d;

// declare reference variables

int&

double& s = d;

r = i;

i = 5;

cout << "Value of i : " << i << endl;

cout << "Value of i reference : " << r << endl;

d = 11.7; cout << "Value of d : " << d << endl; cout
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;

}

When the above code is compiled together and executed, it produces the following result:

Value of i : 5

Value of i reference : 5

Value of d : 11.7

Value of d reference : 11.7

References are usually used for function argument lists and function return values. So

following are two important subjects related to C++ references which should be clear to a

C++ programmer: we can implement call by reference concept using pointers.

Here is another example of call by reference which makes use of C++ reference: #include <iostream.h>

// function declaration

void swap(int& x, int&

y); int main ()

{

// local variable declaration: int a = 100;

int b = 200;

cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl;

27

www.cseitquestions.in

/* calling a function to swap the values.*/ swap(a, b);

cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl;

return 0;

}

int temp; temp = x; /* save the value at address x */ x =
int temp;
temp = x; /* save the value at address x
*/ x = y; /* put y into x */
y = temp; /* put x into y */
return;

// function definition to swap the values. void swap(int& x, int& y)

{

}

When the above code is compiled and executed, it produces the following result: Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

1.12 ROLE OF this POINTER:

Every object in C++ has access to its own address through an important pointer called

this pointer. The this pointer is an implicit parameter to all member functions. Therefore,

inside a member function, this may be used to refer to the invoking object.

Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.

Example:

#include <iostream.h>

28

www.cseitquestions.in

class Box

{

public:

// Constructor definition

Box(double l=2.0, double b=2.0, double h=2.0)

{

cout <<"Constructor called." << endl; length = l; breadth = b; height = h; }
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
Box Box1(3.3, 1.2, 1.5);
// Declare box1
Box Box2(8.5, 6.0, 2.0);
// Declare box2

};

int main(void)

{

if(Box1.compare(Box2))

{

cout << "Box2 is smaller than Box1" <<endl;

}

else

{

29

www.cseitquestions.in

cout << "Box2 is equal to or larger than Box1" <<endl;

}

return 0;

}

When the above code is compiled and executed, it produces the following result: Constructor called.

Constructor called.

Box2 is equal to or larger than Box1

1.13 STORAGE CLASS:

1. Automatic 2. External 3. Static
1. Automatic
2. External
3. Static

the variables defined inside a function are automatic variables.

For instance:

void exforsys( )

{

auto int x;

auto float y;

Storage class defined for a variable determines the accessibility and longevity of the

variable. The accessibility of the variable relates to the portion of the program that has access

to the variable. The longevity of the variable refers to the length of time the variable exists

within the program.

Types of Storage Class Variables in C++:

Automatic:

Variables defined within the function body are called automatic variables. Auto is the

keyword used to declare automatic variables. By default and without the use of a keyword,

}

is the same as

30

www.cseitquestions.in

void exforsys( )

{

int x;

float y;

//Automatic Variables

}

In the above function, the variable x and y are created only when the function exforsys( ) is called. An automatic variable is created only when the function is called. When the function exforsys( ) is called, the variables x and y are allocated memory automatically.

#include <iostream.h> using namespace std; int exforsys(int);
#include <iostream.h>
using namespace std;
int exforsys(int);

For example:

int exforsys2(int); void main( )

External:

External variables are also called global variables. External variables are defined outside any function, memory is set aside once it has been declared and remains until the end of the program. These variables are accessible by any function. This is mainly utilized when a programmer wants to make use of a variable and access the variable among different function calls.

Static:

The static automatic variables, as with local variables, are accessible only within the function in which it is defined. Static automatic variables exist until the program ends in the same manner as external variables. In order to maintain value between function calls, the static variable takes its presence.

{

int in;

int out;

while(1)

{

31

www.cseitquestions.in

cout << "nEnter input value:"; cin>>in;

if (in == 0) break;

out=exforsys(in);

cout << "nResult : " << out; out=exforsys2(in);

cout << "nResult2: " << out; } cout << "n End of Program " ;
cout << "nResult2: " << out;
}
cout << "n End of Program " ;
}
int exforsys(int x)
{
static int
a=0; a++;
return(a);
}
int exforsys2(int x)
{
int b=0;
b++;
return(b);
}

1.14 FUNCTION AS ARGUMENTS:

In the above program, the static variables a is initialized only once in the beginning of the program. Then the value of the variable is maintained between function calls.

A function pointer (or subroutine pointer or procedure pointer) is a type of pointer

supported by third-generation programming languages Instead of referring to data values, a

function pointer points to executable code within memory. When dereferenced, a function

pointer can be used to invoke the function it points to and pass it arguments just like a normal

function call. Such an invocation is also known as an "indirect" call, because the function is

being invoked indirectly through a variable instead of directly through a fixed name or

32

www.cseitquestions.in

address. Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values.

#include <iostream.h>

int add(int first, int second)

{

return first + second;

a, b;
a, b;

}

int subtract(int first, int second)

{

return first - second;

}

int operation(int first, int second, int (*functocall)(int, int))

{

}

return (*functocall)(first, second);

void main()

{

int

int (*plus)(int, int) = add;

int (*minus)(int, int) = subtract; a = operation(7, 5, plus);

b = operation(20, a, minus);

cout << "a = " << a << " and b = " << b <<

"a = " << a << " and b = " << b << endl; }

endl; }

33

www.cseitquestions.in

UNIT II

OBJECT ORIENTED PROGRAMMING CONCEPTS

String Handling Copy Constructor - Polymorphism compile time and run time

polymorphisms function overloading operators overloading dynamic memory

allocation - Nested classes - Inheritance virtual functions.

C++ provides following two types of string representations:  The C-style character string.  
C++ provides following two types of string representations:
 The C-style character string. 
 The string class type introduced with Standard C++. 
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

containing the string is one more than the number of characters in the word "Hello."

2.1 STRING HANDLING:

2.1.1 The C-Style Character String:

The C-style character string originated within the C language and continues to be

supported within C++. This string is actually a one-dimensional array of characters which is

terminated by a null character '\0'. Thus a null-terminated string contains the characters that

comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word

"Hello". To hold the null character at the end of the array, the size of the character array

If you follow the rule of array initialization, then you can write the above statement as follows:

Following is the memory presentation of above defined string in C/C++:

34

www.cseitquestions.in

Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array.

#include <iostream.h> int main ()

{

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: "; cout << greeting << endl; return 0;  Copies string
cout << "Greeting message:
"; cout << greeting << endl;
return 0;
Copies string s2 into string s1. 
Concatenates string s2 onto the end of string s1. 
Returns the length of string s1. 
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. 
Returns a pointer to the first occurrence of character ch in string s1. 

}

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings:

strcpy(s1,s2);

strcat(s1,s2);

strlen(s1);

strcmp(s1,s2);

strchr(s1,ch);

strstr(s1,s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions:

#include <iostream.h>

#include <cstring.h>

int main ()

35

www.cseitquestions.in

{

char str1[10] = "Hello";

char str2[10] =

"World"; char str3[10];

int len ;

// copy str1 into str3 strcpy( str3, str1);

cout << "strcpy( str3, str1) : " << str3 << endl; // concatenates str1 and
cout << "strcpy( str3, str1) : " << str3 << endl;
// concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 <<
endl; // total lenghth of str1 after
concatenation len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
return 0;

}

When the above code is compiled and executed, it produces result something as follows:

strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10

2.1.2 The String Class in C++:

The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality.

#include <iostream.h> #include <string.h> int main ()

{

string str1 = "Hello";

string str2 = "World";

string str3;

int len ;

// copy str1 into str3

36

www.cseitquestions.in

str3 = str1;

cout << "str3 : " << str3 << endl;

// concatenates

str2 str3 = str1 + str2;

cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation len = str3.size();

str1

and

cout << "str3.size() : " << len << endl; return 0; Exforsys e3(e2); or Exforsys
cout << "str3.size() : " << len << endl;
return 0;
Exforsys e3(e2);
or
Exforsys e3=e2;

}

When the above code is compiled and executed, it produces result something as follows:

str3 : Hello

str1 + str2 : HelloWorld str3.size() : 10

2.2 COPY CONSTRUCTOR:

This constructor takes one argument, also called one argument constructor. The main

use of copy constructor is to initialize the objects while in creation, also used to copy an

object. The copy constructor allows the programmer to create a new object from an existing

one by initialization.

For example to invoke a copy constructor the programmer writes:

Both the above formats can be sued to invoke a copy constructor.

For Example:

#include <iostream.h>

using namespace std;

class Exforsys

{

private:

37

www.cseitquestions.in

int a;

public:

Exforsys()

{

}

Exforsys(int w)

{

a=w; } Exforsys(Exforsys& e) { a=e.a; cout << " Example of Copy Constructor"; } void
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout << " Example of Copy Constructor";
}
void result()
{
cout<< a;
}
};
void main()
{
Exforsys e1(50);
Exforsys e3(e1);
cout<< "ne3=";
e3.result();
}

2.3 POLYMORPHISM:

Polymorphism is one of the most important features of Object Oriented Programming.

Polymorphic variables can take up objects or values of different types as values and

polymorphic functions and procedures can be used as objects or values of different types. It

refers to exhibiting different behaviour by an instance in different situations.

Polymorphism is implemented through,

38

www.cseitquestions.in

1. Function overloading

2. Operator overloading.

2.4 COMPILE TIME AND RUNTIME

2. Operator overloading. 2.4 COMPILE TIME AND RUNTIME POLYMORPHISM: Compile time Polymorphism:  Compile time

POLYMORPHISM: Compile time Polymorphism:

Compile time Polymorphism also known as method overloading.

  Method overloading means having two or more methods with the same name but
 Method overloading means having two or more methods with the same name
but with different signatures. 
Run time Polymorphism:
 Run time Polymorphism also known as method overriding. 
 Method overriding means having two or more methods with the same name,
same signature but with different implementation. 
Overloading is a form of polymorphism. In case of function overloading, the
information regarding which function is to be invoked corresponding to a function call is
available at compile time. This is referred to as static binding or compile time polymorphism,
as the object is bound with its function call at compile time.
Run time polymorphism is achieved through virtual functions. The function to be
invoked by the instance of a class is known during runtime. The functions are linked with the
class during runtime and not during compile time. When a base class pointer points to a sub
class instance, instead of invoking subclass function (a function having name similar to that
of function of a base class), it always invokes base class version. If the function in the base
class is defined as virtual, then it is known during runtime only, which version of the function
will be invoked, corresponding to a function call. Since the function is linked after
compilation process, it is termed as late binding or dynamic binding or run-time
polymorphism.

2.5 FUNCTION OVERLOADING:

It is also referred to as functional polymorphism. The same function can perform a

wide variety of tasks. The same function can handle different data types. When many

functions with the same name but different argument lists are defined, then the function to be

invoked corresponding to a function call is known during compile time.

39

www.cseitquestions.in

When the source code is compiled, the functions to be invoked are bound to the

compiler during compile time, as to invoke which function depending upon the type and

number of arguments. Such a phenomenon is referred to early binding, static linking or

compile time polymorphism.

For example:

#include <iostream.h> //function prototype

int multiply(int num1, int num2);

float multiply(float num1, float num2); void main()

{

//function call statements int ans1=multiply(4,3);

// first prototype is invoked as arguments

// are of type int

float ans2 = multiply(2.5, 4.5);

//second prototype is
//second prototype is

reported at compile time, hence referred to as compile time polymorphism.

2.6 OPERATOR OVERLOADING:

invoked as arguments are of type float

}

The compiler checks for the correct function to be invoked by matching the type of

arguments and the number of arguments including the return type. The errors, if any, are

Operator overloading is a very important feature of Object Oriented Programming.

Curious to know why!!? It is because by using this facility programmer would be able to

create new definitions to existing operators. In other words a single operator can take up

several functions as desired by programmers depending on the argument taken by the

operator by using the operator overloading facility.

Broadly classifying operators are of two types namely:

Unary Operators

Binary Operators

40

www.cseitquestions.in

Unary Operators:

As the name implies, it operates on only one operand. Some unary operators are

named ++ also called the Increment operator, -- also called the Decrement Operator, ! , ~ are

called unary minus.

Binary Operators:

It operates on two operands. Some binary operators are arithmetic  return_type - is the
It
operates
on
two
operands.
Some
binary operators
are
arithmetic
return_type - is the data type returned by the function 
class name - is the name of the class 
operator - is the keyword 
operator symbol - is the symbol of the operator which is being overloaded or
defined for new functionality 
:: - is the scope resolution operator which is used to use the function definition

The general syntax for defining an operator overloading is as follows:

return_type classname :: operator operator_symbol(argument)

{

…….

In the above:

outside the class. The usage of this is clearly defined in our earlier section of How

to define class members.

operators,

comparison operators, and arithmetic assignment operators.

2.6.1 Operator Overloading - Unary operators

Operator overloading helps the programmer to define a new functionality for the existing operator. This is done by using the keyword operator.

Statements;

}

Operator overloading is defined as a member function by making use of the keyword operator.

For example

Suppose we have a class say Exforsys and if the programmer wants to define a operator overloading for unary operator say ++, the function is defined as,

41

www.cseitquestions.in

class Exforsys { private: … public: void operator ++(); ……. }; Inside the class Exforsys

class Exforsys

{

private:

public:

void operator ++();

…….

};

Inside the class Exforsys the data type that is returned by the overloaded operator is defined as,

The important steps involved in defining an operator overloading in case of unary operators are:

Inside the class the operator overloaded member function is defined with the return

data type as member function or a friend function. The concept of friend function we will

define in later sections. If in this case of unary operator overloading if the function is a

member function then the number of arguments taken by the operator member function is

none as seen in the below example. In case if the function defined for the operator

overloading is a friend function which we will discuss in later section then it takes one

argument.

The operator overloading is defined as member function outside the class using the scope resolution operator with the keyword operator.

#include <iostream.h> using namespace std;
#include <iostream.h>
using namespace std;

42

www.cseitquestions.in

class Exforsys { private: int x; public: Exforsys( ) { x=0; } //Constructor void display();
class Exforsys
{
private:
int x;
public:
Exforsys( ) { x=0; } //Constructor
void display();
void operator ++( );
};
void Exforsys :: display()
{
cout << "nValue of x is: " << x;
}
void Exforsys :: operator ++( ) //Operator Overloading for operator ++ defined
{
++x;
}
void main( )
{
Exforsys e1,e2; //Object e1 and e2 created
cout << "Before Increment";
cout << "nObject e1: "; e1.display();
cout << "nObject e2: "; e2.display();
++e1; //Operator overloading applied
++e2;
cout << "n After Increment";
cout << "nObject e1: "; e1.display();
cout << "nObject e2: "; e2.display();
}

43

www.cseitquestions.in

In the above example we have created 2 objects e1 and e2 f class Exforsys. The operator ++ is overloaded and the function is defined outside the class Exforsys.

When the program starts the constructor Exforsys of the class Exforsys initialize the

values as zero and so when the values are displayed for the objects e1 and e2 it is displayed

as zero. When the object ++e1 and ++e2 is called the operator overloading function gets

applied and thus value of x gets incremented for each object separately. So now when the

values are displayed for objects e1 and e2 it is incremented once each and gets
values are displayed for objects e1 and e2 it is incremented once each and gets printed as one
for each object e1 and e2.
2.6.2 Operator Overloading - Binary Operators
Binary operators, when overloaded, are given new functionality. The function defined
for binary operator overloading, as with unary operator overloading, can be member function
or friend function.
The difference is in the number of arguments used by the function. In the case of
binary operator overloading, when the function is a member function then the number of
arguments used by the operator member function is one (see below example). When the
function defined for the binary operator overloading is a friend function, then it uses two
arguments.
Binary operator overloading, as in unary operator overloading, is performed using a
keyword operator.
Binary operator overloading example:
Sample Code
#include <iostream>
using namespace std;
class Exforsys
{
private:
int x;
int y;
public:

44

www.cseitquestions.in

Exforsys() //Constructor { x=0; y=0; } void getvalue( ) //Member Function for Inputting Values {
Exforsys()
//Constructor
{ x=0; y=0; }
void getvalue( )
//Member Function for Inputting Values
{
cout << "n Enter value for x: ";
cin >> x;
cout << "n Enter value for y: ";
cin>> y;
}
void displayvalue( )
//Member Function for Outputting Values
{
cout << "value of x is: " << x << "; value of y is: " << y;
}
Exforsys operator +(Exforsys);
};
Exforsys Exforsys :: operator + (Exforsys e2)
{
Exforsys rez; //declaring an Exforsys object to retain the final values
int x1 = x+ e2.x;
int y1 = y+e2.y;
rez.x=x1;
rez.y=y1;
return rez;
}
void main( )
{
Exforsys e1,e2,e3;
//Objects e1, e2, e3 created
cout << "nEnter value for Object e1:";
e1.getvalue( );

45

www.cseitquestions.in

cout << "nEnter value for Object e2:"; e2.getvalue( ); e3= e1+ e2; //Binary Overloaded operator
cout << "nEnter value for Object e2:";
e2.getvalue( );
e3= e1+ e2; //Binary Overloaded operator used cout <<
"nValue of e1 is: "; e1.displayvalue();
cout << "nValue of e2 is: " ; e2.displayvalue();
cout << "nValue of e3 is: "; e3.displayvalue();
}
In the above example, the class Exforsys has created three objects e1, e2, e3. The
values are entered for objects e1 and e2. The binary operator overloading for the operator '+'
is declared as a member function inside the class Exforsys. The definition is performed
outside the class Exforsys by using the scope resolution operator and the keyword operator.
e3= e1 + e2; The binary overloaded operator '+' is used. In this statement, the
argument on the left side of the operator '+', e1, is the object of the class Exforsys in which
the binary overloaded operator '+' is a member function. The right side of the operator '+' is
e2. This is passed as an argument to the operator '+' . Since the object e2 is passed as
argument to the operator '+' inside the function defined for binary operator overloading, the
values are accessed as e2.x and e2.y. This is added with e1.x and e1.y, which are accessed
directly as x and y. The return value is of type class Exforsys as defined by the above
example.
There are important things to consider in operator overloading with C++ programming
language. Operator overloading adds new functionality to its existing operators. The
programmer must add proper comments concerning the new functionality of the overloaded
operator. The program will be efficient and readable only if operator overloading is used only
when necessary.

Some Operators that cannot be downloaded:

scope resolution operator denoted by ::   Member access operator or the dot operator
scope resolution operator denoted by :: 
Member access operator or the dot operator denoted by . 
The conditional operator denoted by ?: 
And pointer to member operator denoted by .* 

46

www.cseitquestions.in

2.7 DYNAMIC MEMORY ALLOCATION:

Memory in C++ program is divided into two parts:

The stack: All variables declared inside the function will take up memory from

the stack.

The heap: This is unused memory of the program and can be used to allocate the

memory dynamically when program runs.

Many times, we are not aware in advance how much memory you will need to store

particular information in a defined variable and the size of required memory can be

We can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This

1. determined at run time. 2. operator is called new operator. There is following generic
1.
determined at run time.
2.
operator is called new operator.
There
is
following
generic
syntax
to
use
new
operator
to
allocate
new data-type;

time.

We can do this using the new operator with the following statements: double* pvalue = NULL; // Pointer initialized with null

pvalue = new double; // Request memory for the variable

If we are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory previously allocated by new operator.

The new and delete operators:

dynamically for any data-type.

memory

Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution

The memory may not have been allocated successfully, if the free store had been used

up. So it is good practice to check if new operator is returning NULL pointer and take

appropriate action as below:

double* pvalue = NULL;

47

www.cseitquestions.in

if( !(pvalue = new double ))

{

cout << "Error: out of memory." <<endl; exit(1); }

Example:

#include <iostream.h> int main ()

double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue;
// free up the memory.
return 0;

dynamically as shown below.

char* pvalue = NULL; // Pointer initialized with null pvalue = new char[20]; // Request memory for the variable

To remove the array that we have just created the statement would look like this:

delete [] pvalue; // Delete array pointed to by pvalue

{

}

If we compile and run above code, this would produce the following result:

Value of pvalue : 29495

Dynamic Memory Allocation for Arrays:

Consider if we want to allocate memory for an array of characters, i.e., string of 20

characters. Using the same syntax what we have used above we can allocate memory

Following the similar generic syntax of new operator, you can allocat for a multi- dimensional array as follows:

double** pvalue = NULL; // Pointer initialized with null pvalue = new double [3][4]; // Allocate memory for a 3x4 array

48

www.cseitquestions.in

However, the syntax to release the memory for multi-dimensional array will still remain same as above:

delete [] pvalue;

// Delete array pointed to by pvalue

Dynamic Memory Allocation for Objects:

Objects are no different from simple data types. For example, consider the following public: Box()
Objects are no different from simple data types. For example, consider the following
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;

code where we are going to use an array of objects to clarify the concept:

#include <iostream.h> class Box

{

};

int main( )

{

}

If we were to allocate an array of four Box objects, the Simple constructor would be

called four times and similarly while deleting these objects, destructor will also be called

same number of times.

If we compile and run above code, this would produce the following result:

Constructor called!

Constructor called!

49

www.cseitquestions.in

Constructor called!

Constructor called!

Destructor called!

Destructor called!

Destructor called!

Destructor called!

 A class that contains the definition of another class called nesting class and the
 A class that contains the definition of another class called nesting class and the class
inside the nesting class called nested class.
 Nested classes can directly use names, type names, names of static members, and 
must use pointers, references, or object names.
 The nesting of classes enables building of powerful data structures.

2.8 NESTED CLASSES:

The nesting class can access the data member and function member of a nested class.

enumerators only from the enclosing class. To use names of other class members, you

Syntax

class Nesting_Class

{

Public:

Data Members of Nesting Class; class Nested_Class

{

public:

Data Member of Nested Class

Function Members of Nested

Class }; };

void main()

{

Nesting_class::Nested_class Object; object.Nested_class Datamember=value; object.Nested_class Functionmember();

}

50

www.cseitquestions.in

Example:

#include<iostream.h>

#include<conio.h>

class fxclg //Nesting Class { public: class cse //Nested Class { public: char name[10],dept[5]; int
class fxclg
//Nesting Class
{
public:
class cse
//Nested Class
{
public:
char name[10],dept[5];
int age;
void get()
{
cout<<"Enter Details Name Age Dept:\n";
cin>>name;
cin>>age;
cin>>dept;
cout<<"\n";
}
void put()
{
cout<<"name\t"<<name<<"age:\t"<<age<<"dept:\t"<<dept;
}
};
};
void main()
{
clrscr();

fxclg::cse cs1; //Declaring Object for Nested Class

cs1.get();

cs1.put();

getch();

}

51

www.cseitquestions.in

Output:

Enter Details Name Age Dept:

kumar

24

CSE

kumar age: 24 dept: CSE
kumar age:
24 dept: CSE

Using this object it access the data and function member of nested class cse

2.9 INHERITANCE:

name

In this example, the class cse (nested class) is defined within the class fxclg(nesting

class),To declare the objects of a nested class we have to follow the procedure, fxclg::cse c1;

One of the most important concepts in object-oriented programming is that of

inheritance. Inheritance allows us to define a class in terms of another class, which makes it

easier to create and maintain an application. This also provides an opportunity to reuse the

code functionality and fast implementation time.

When creating a class, instead of writing completely new data members and member

functions, the programmer can designate that the new class should inherit the members of an

existing class. This existing class is called the base class, and the new class is referred to as

the derived class.

The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Base & Derived Classes:

A class can be derived from more than one classes, which means it can inherit data

and functions from multiple base classes. To define a derived class, we use a class derivation

list to specify the base class(es). A class derivation list names one or more base classes and

has the form:

class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class is the

name of a previously defined class. If the access-specifier is not used, then it is private by

default.

52

www.cseitquestions.in

Type of Inheritance:

Single Inheritance

Multiple Inheritance

Multilevel Inheritance

Hybrid Inheritance

Hierarchical Inheritance

Inheritance   Hierarchical Inheritance  2.9.1 Single Inheritance: Example:

2.9.1 Single Inheritance:

Example:

#include<iostream.h>

#include<conio.h> class student

{

public:

char name[10],collname[10],dept[5];

void getfun()

{

cout<<"Enter Name,College,Department\n"; cin>>name>>collname>>dept;

}

};

class cse:public student

{

public:

53

www.cseitquestions.in

char sub1[5],sub2[5],sub3[5]; void getdet()

{

getfun();

cout<<"Enter subject 1,2,3";

cin>>sub1>>sub2>>sub3;

}

1,2,3"; cin>>sub1>>sub2>>sub3; } void putdet() {

void putdet()

{

cout<<"Name\t"<<name<<"College name\n"<<collname<<"Department\t"<<dept <<"Subject 1,2,3\t"<<sub1<<sub2<<sub3;

}

};

void main()

{

clrscr();

cse c1;

c1.getdet();

c1.putdet();

getch();

}

Output:

Enter Name,College,Department paul

fx

cse

Enter subject 1,2,3 maths

pds

evs

Name

paul College name fx Department cse subject 1,2,3 maths pds evs

54

www.cseitquestions.in

2.9.2 Multiple Inheritance

2.9.2 Multiple Inheritance A derived class with several base classes is called multiple inheritance. Example:

A derived class with several base classes is called multiple inheritance.

Example:

#include<iostream.h>

#include<conio.h> class student

{

public:

char name[10],collname[10],dept[5]; void getfun()

{

cout<<"Enter name,college name,department\n"; cin>>name>>collname>>dept;

}

};

class internal

{

public:

char sub1[5],sub2[5],sub3[5]; int im1,im2,im3;

void getdet()

{

cout<<"Enter subject 1,2,3\n";

cin>>sub1>>sub2>>sub3;

cout<<"Enter internal marks for subject1,2,3\n";

55

www.cseitquestions.in

cin>>im1>>im2>>im3;

}

};

class cse:public internal,public student

{

public:

} }; class cse:public internal,public student { public: int ex1,ex2,ex3,t1,t2,t3; void calc() { getfun(); getdet();

int ex1,ex2,ex3,t1,t2,t3; void calc()

{

getfun();

getdet();

cout<<"Enter external marks for subject1,2,3\n"; cin>>ex1>>ex2>>ex3;

t1=ex1+im1;

t2=ex2+im2;

t3=ex3+im3;

}

void putdet()

{

cout<<"\nname\t"<<name<<"collname\t"<<collname<<"dept\t"<<dept<<"\n" <<"sub1 Total\t"<<t1<<"sub2\t"<<t2<<"sub3\t"<<t3<<"\n";

}

};

void main()

{

clrscr();

cse c1;

c1.calc();

c1.putdet();

getch();

}

56

www.cseitquestions.in

Output:

Enter name,college name,department

paul

fx

cse

Enter subject 1,2,3

maths

pds dbms Enter internal marks for subject1,2,3 50 50 50 Enter external marks for subject1,2,3
pds
dbms
Enter internal marks for subject1,2,3
50
50
50
Enter external marks for subject1,2,3
50
50
50
name paul
collname
fx
dept cse
sub1
Total
100
sub2 100
sub3 100
2.9.3 Multilevel Inheritance

The mechanism of deriving a class from another derived class is known as multilevel inheritance.

57

www.cseitquestions.in

STUDENT TEST RESULT
STUDENT
TEST
RESULT

Example:

#include<iostream.h>

#include<conio.h>

#include<iomanip.h> class student

{

public:

char name[10],clgname[10];

int age,year;

void get()

{

cout<<"Enter the Name,College Name,Age, Year:\n"; cin>>name>>clgname>>age>>year;

}

void put()

{

cout<<"Name:\t"<<"College Name:\t"<<"Age:\t" <<"Year:\t"<<"\n";

cout<<name<<"\t"<<clgname<<"\t"<<age<<"\t"<<year<<"\n";

}

};

class test:public student

{

public:

int m1,m2,m3;

void getmarks()

58

www.cseitquestions.in

{

cout<<"Enter mark1,2,3";

cin>>m1>>m2>>m3;

}

void putmarks()

{

cout<<"Mark1:\t"<<"Mark2\t"<<"Mark3\t"<<"\n";

cout<<m1<<"\t"<<m2<<"\t"<<m3<<"\n";

}

};

class result:public test

{

public:

int i1,i2,i3,t1,t2,t3;

void getinternal()

{

cout<<"Enter the internal marks:"; cin>>i1>>i2>>i3;

}

void finalmark()

{

t1=i1+m1;

t2=i2+m2;

t3=i3+m3;

cout<<"Result M1,M2,M3:";

cout<<"\t"<<t1<<"\t"<<t2<<"\t"<<t3<<"\n";

}

};

void main()

{

clrscr();

result r1;

r1.get();

59

www.cseitquestions.in

r1.getmarks();

r1.getinternal();

r1.put();

r1.putmarks();

r1.finalmark();

getch();

}

r1.put(); r1.putmarks(); r1.finalmark(); getch(); } In this example the student class is derived into test class

In this example the student class is derived into test class and then the test class further derived into result class. So the result class inherits the properties of both student and

the result class inherits the properties of both student and test class. 2.9.4 Hierarchical Inheritance are
test class. 2.9.4 Hierarchical Inheritance are derived from common base class. Example: #include <iostream.h>
test class.
2.9.4 Hierarchical Inheritance
are derived from common base class.
Example:
#include <iostream.h>
class Side
{
public:
int l;

Hierarchical Inheritance is a method of inheritance where one or more derived classes

void set_values (int x)

{

l=x;

}

};

class Square: public Side

60

www.cseitquestions.in

{

public:

int sq()

{

return (l *l);

}

};

class Cube:public Side { public: int cub() { return (l *l*l); } }; int main
class Cube:public Side
{
public:
int cub()
{
return (l *l*l);
}
};
int main ()
{
Square s;
s.set_values (10);
cout << "The square value is::" << s.sq() <<
endl; Cube c;
c.set_values (20);
cout << "The cube value is::" << c.cub() << endl;
return 0;
}
Output:

The square value is:: 100

The cube value is::8000

In the above example the two derived classes "Square", "Cube" uses a single base

class "Side". Thus two classes are inherited from a single class. This is the hierarchical

inheritance OOP's concept in C++.

61

www.cseitquestions.in

2.9.5 Hybrid Inheritance

Hybrid inheritance is combination of two or more inheritances such as single, multiple, multilevel.

Example: #include <iostream.h> class mm { protected: int rollno; public: void get_num(int a) { rollno
Example:
#include <iostream.h>
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{
rollno = a;
}
void put_num()
{
cout << "Roll Number Is:"<< rollno << "\n";
}
};
class marks : public mm
{
protected: int sub1; int sub2; public:
protected:
int sub1;
int sub2;
public:

void get_marks(int x,int y)

62

www.cseitquestions.in

{ sub1 = x; sub2 = y; } void put_marks(void)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{ cout << "Subject 1:"; cout<< sub1 ; cout<< "\n"; cout <<
{
cout << "Subject 1:";
cout<< sub1 ;
cout<< "\n";
cout << "Subject 2:";
cout << sub2;
cout << "\n";
}
};
class extra
{
protected:
float e;
public:
void get_extra(float s)
{
e=s;
}
void put_extra(void)
{
cout << "Extra Score::" <<
e; cout<< "\n";
}
};

class res : public marks, public extra

{ protected: float tot;
{
protected:
float tot;

63

www.cseitquestions.in

public: void disp(void) { tot = sub1+sub2+e;
public:
void disp(void)
{
tot = sub1+sub2+e;
put_num(); put_marks(); put_extra(); cout << "Total:"<< tot; } }; int main() { res std1;
put_num();
put_marks();
put_extra();
cout << "Total:"<< tot;
}
};
int main()
{
res std1;
std1.get_num(10);
std1.get_marks(10,20);
std1.get_extra(33.12);
std1.disp();
return 0;
}
Output:
Roll Number Is: 10
Subject 1: 10
Subject 2: 20
Extra score:33.12
Total: 63.12

2.10 VIRTUAL FUNCTIONS:

If there are member functions with same name in base class and derived class, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important features of OOP.

64

www.cseitquestions.in

If a base class and derived class has same function and if you write code to access that function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable.

Example:

#include <iostream.h> class CPolygon

{ public: int width, height; void set_values (int a, int b) { width=a; height=b; }
{
public:
int width, height;
void set_values (int a, int b)
{
width=a; height=b;
}
virtual int area ( )
{
Cout<<”Base Class Area of CPolygon”;
};
class CRectangle: public CPolygon
{
public:
int area (void)
{
return (width * height);
}
};
class CTriangle: public CPolygon

{

public:

int area ( )

{

return (width * height / 2);

}

65

www.cseitquestions.in

};

void main ()

{

CRectangle rect;

CTriangle trgl;

CPolygon * ppoly1 = &rect; CPolygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area( ) << endl;
cout << ppoly2->area( ) << endl;
}
Output:
20
10
derived class function area().

In this example class CPolygon includes a virtual function area( ). In this function we

included the cout statement. When the base class pointer have derived class object and if the

pointer points the function area() then the base class area() function is overloaded with the

66

www.cseitquestions.in

UNIT III

C++ PROGRAMMING ADVANCED FEATURES

Abstract class Exception handling - Standard libraries - Generic Programming -

templates class template - function template STL containers iterators function

adaptors allocators -Parameterizing the class - File handling concepts.

3.1 ABSTRACT CLASS The purpose of an abstract class (often referred to as an ABC)
3.1 ABSTRACT CLASS
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used
to instantiate objects and serves only as an interface. Attempting to instantiate an object of an
abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be
instantiated, it has to implement each of the virtual functions, which means that it supports
the interface declared by the ABC. Failure to override a pure virtual function in a derived
class, then attempting to instantiate objects of that class, is a compilation error. Classes that
can be used to instantiate objects are called concrete classes.
3.2 EXCEPTION HANDLING
An exception is any unusual event, either erroneous or not, detectable by either
hardware or software, that may require special processing.
WITHOUT EXCEPTION HANDLING
WITH EXCEPTION HANDLING
When an exception occurs, control goes to the
 are
Programs
allowed
to
trap
operating system, where typically
exceptions.
 an error message is displayed
 There is a possibility to fix the
 the program is terminated
problem and continuing execution

Exception handling mechanism

To detect and report error, The error handling code performs the following task

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)

67

www.cseitquestions.in

4. Take corrective actions. (Handle the exception).

Keywords in Exception Handling

try

throw

catch

TRY BLOCK -The keyword try is used to preface a block of statements (surrounded by braces) which may generate exceptions.

->When an exception is detected, it is thrown using a throw statement in the try
->When an exception is detected, it is thrown using a throw statement in the try block.

CATCH BLOCK - defined by the keyword catch „catches‟ the exception „thrown‟

by the throw statement in the try block, and handles it appropriately.

Exception Handling Syntax:

try

//try block

{

…….

throw exception;

// Block of statements which detects and throws an exception

68

www.cseitquestions.in

}

catch(type arg) // Catches exception

{

…….

……

}

// Block of statements that handles the exception

Example: #include <iostream> int main() cout << “start”; try { // start a try block
Example:
#include <iostream>
int main()
cout << “start”;
try
{
// start
a try block cout << Inside try
block\n”;
throw 100;
// throw an error
cout << “This will not execute”;
}
catch (int i)
{
// catch an error
cout << “caught an exception
“; cout << i ; cout << “End”;
return 0;
}
}

Exception Types Synchronous Exception:

Out of range

Over flow

Asynchronous Exception

Error that are caused beyond the control of the program

Keyboard interrupts

69

www.cseitquestions.in

In C++ only synchronous exception can be handled.

Factors determining Exception

Division by zero

Access to an array outside of its bounds

Running out of memory

 Running out of disk space   Dividing the error handling   Unconditional
 Running out of disk space 
 Dividing the error handling 
 Unconditional termination & programmer preferred termination 
 Separating error reporting and error handling 
 Object destroy problem 
#include<iostream.h>
int main()
{
int i,j;
cout << "Starts here\n"; i=10;
catch( int a)
{ // catch an error
cout << "The Number Caught is : ";
cout << a << "\n";
}
j=0;
try
cout << "Ends here";
return 0;
{
}
// start a try block
cout << "Inside try block\n";
if(j==0)
{

Need for Exception Handling

throw j; // throw an error cout << "This will not be printed \n"; }

cout<<”RESULT IS “<<i/j;

}

When the program enters the try block it is said to be in the guarded section.

In this program when the value of j is zero an exception is created and thrown.

70

www.cseitquestions.in

Note that the statement after throw statement in try block is not executed.

Once the exception is thrown the catch block catches the value (here zero) and handles it.

After that the program continues its normal execution.

Functions Generating Exceptions

C++ allows functions to generate exceptions. These functions cannot be called as an ordinary function.
C++ allows functions to generate exceptions. These functions cannot be called as an ordinary
function. Enclose the function call with a try catch block.
Syntax:
try
{ function(arg);
}
catch(type arg)
{
------
}
#include<iostream.h>
void main()
void compute(int a,int b)
{
{
int x,y;
int c; if(b==0)
cout<<”ENTERTWONUMBERS”;
{
cin>>x>y;
throw b;
try
else
{
c=a/b;
compute(x/y); // fun generating exception
}
}
cout<<”RESULT OF THE DIVISION”<<c;
catch(int k)
}
{
cout<<”Divide By Zero exception”;
}
}
71

www.cseitquestions.in

Throwing Mechanisms:

An exception is thrown by using the throw keyword from inside the try block.

A throw expression accepts one parameter, which is passed as an argument to the

exception handler.

Eg. throw b;

The throw statement will have the following.

Example:  throw (exception)   throw exception   throw  If the data
Example:
throw (exception) 
throw exception 
throw
If the data type specified by a catch, matches that of the exception, then catch
statement is executed. 
When an exception is caught, arg will receive its value 
A
try
can
have
multiple
catches 
If there are multiple catches for a try, only one of the matching catch is selected and
that corresponding catch block is executed. 
Syntax:
try
{
any statements
if (some condition) throw

Catching Mechanisms

Multiple Catch Statements

value1; else if (some other

condition) throw value2;

else if (some last condition) throw valueN;

}

catch (type1 name)

72

www.cseitquestions.in

{

any statements

}

catch (type2 name)

{

any statements

}

catch (typeN name) { any statements } Example: #include<iostream.h> void multiple_catch(int value) { try
catch (typeN name)
{
any statements
}
Example:
#include<iostream.h>
void multiple_catch(int value)
{
try
{
if (value==0) //throw an int value
throw 1;
else if (value==1) //throw a char
throw „a‟;
else //throw float
throw 1.1;
}
catch(char c)
{

cout<<”Character value is thrown” <<c;

}

catch(int i)

{

cout<<”Integer value is thrown”<<i;

}

catch(float f)

73

www.cseitquestions.in

{

cout<<”Float value is thrown”<<f;

}

}

void main()

{

cout<<”Main Program”<<endl; multiple_catch(0); multiple_catch(1); multiple_catch(5); } try {
cout<<”Main Program”<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
try
{
….
throw a;
}
catch (char c)
{
throw;
//rethrow same exception in catch block in main()
}
Example:
#include <iostream.h>
class sam

Rethrowing Exceptions Syntax:

{

int erno;

public:

sam (int errno)

{

exno=errno;

}

74

www.cseitquestions.in

void shoex()

{

cout<<”error no:”<<exno;

}

};

void ergen()

{

try { sam s1(20); int c; cin>>c; switch (c) { case 1: throw 10; case
try
{
sam
s1(20); int
c; cin>>c;
switch (c)
{
case 1:
throw 10;
case 2:
throw „a‟;
case 3:
throw s1;
case 4:
throw “welcome”;
}
catch (int ie)
{
cout<<”ie”<<ie;
throw; //rethrowing

}

catch (char ce)

{

cout <<”ce”<<ce; throw; //rethrowing

}

}

75

www.cseitquestions.in

void main ()

{

try

{

ergen();

throw 10;

}

catch (int) { cout <<”caught integer”; } catch(char) { cout<<”caught char”; } catch (sam
catch (int)
{
cout <<”caught integer”;
}
catch(char)
{
cout<<”caught char”;
}
catch (sam s2)
{
s2.show x();
}
Terminate Function
built-in terminate.
Use:
Used to close all open files & deallocate resources before quitting the program.
Syntax: set_terminate (myterminate);

Terminate () is the function which calls abort() to exit the program in the event of run time

error related to exceptions. The user can provide his or her own terminate function instead of

Unexpected Function

If a function throws an exception which is not allowed, a function unexpected () is called, which in turn calls abort.

We can use set_unexpected in a similar to set_terminate Syntax:

set_unexcepted(my unexcepted);

76

www.cseitquestions.in

Example:

#include <iostream.h> void myunexpected ()

{

cout << "unexpected called\n"; throw 0; // throws int (in exception-specification)

}

}

void myfunction () throw (int) { throw 'x'; // throws char (not in exception-specification) }
void myfunction
() throw (int)
{
throw 'x'; // throws char (not in exception-specification)
}
int main (void)
{
set_unexpected (myunexpected);
try
{
myfunction();
}
catch (int)
{
cout << "caught int\n";
}
catch (
)
{
cout << "caught some other exception type\n";
}

return 0;

Uncaught Exception()

This function returns true if an exception has been thrown but not yet caught.

Once caught, the function returns false.

77

www.cseitquestions.in

Syntax:

bool

uncaught_exceptions.

if

(uncaught_exception(

))

{ //Do not call the function which might throw an exception } Otherwise { Follow
{
//Do not call the function which might throw an exception
}
Otherwise
{
Follow the natural sequence of the destructor Algorithm
}
3.3 STANDARD LIBRARIES:
Streams and Formatted I/O :
A stream is a sequence of bytes (or) conceptually pipe like constructs used for
providing I/O. 
Streams provide consistent interface for providing independence from having different
operations for different IO devices. 
The source stream that provides data to the program is called the input stream. 
The destination stream that receives output from the program is called the output
stream.
C++ STREAM CLASSES:
ios :
It is the base class for istream and ostream. 
 It is declared as the virtual base class. 

It provides the basic support for formatted and unformatted I/O operations.

istream:

Provides facilities for formatted and unformatted input operations.

Functions such as getc(),getline(),read() are declared.

Overloaded extraction operator (>>)

78

www.cseitquestions.in

ostream:

Provides the facilities for formatted and unformatted output operations.

Putc() and write() functions are declared.

Overloaded insertion operator (<<)

streambuf:

It is used to access streams using lower level functions.

 Provides an interface to physical devices through buffers.   Acts as a base
 Provides an interface to physical devices through buffers. 
 Acts as a base class for filebuf class. 
 Provides facilities for handling both input and output streams. 
 Inherits the properties of ios, istream and ostream through multiple inheritance. 
 The >> operator is overloaded in the istream. 
 The << operator is overloaded in the ostream. 
cin>>variable 1>>….>>variable n ;
 getc() and putc() are used for reading and writing to the streams. 
 The getc() function has two different versions
: 1. void get(char) 2. char get(void) 
The put() function is used to display the data. 

iostream:

UNFORMATTED I/O OPERATIONS:

Overloaded operators >> and << :

The input data are separated by white spaces and should match the type of variable in „cin‟. cout<<variable 1<<….<<variable n;

This statement is used for displaying data on the screen.

putc() and getc() functions :

Get() reads a character at a time from the input stream and put() writes a character at a time to the output stream.

getline, read and write functions :

These functions are used for reading and writing strings.

The prototypes for these three functions are :

 

cin.getline(string variable , int size);

 

cin.read(string variable, int size);

cin.write(string variable,int size);

79

www.cseitquestions.in

The difference between getline() and read() is that : getline() terminates when a new line is entered but read() does not stop when a new line is encountered.

read() stops only when end of file (ctrl + z ) is encountered.

The getline() also stops reading from input if end of file is specified.

FORMATTED I/O OPERATIONS:

1. width() :

 it specifies the width for display.   it is used in aligning vertical
it specifies the width for display. 
it is used in aligning vertical columns. 
2. precision() :
it specifies the precision of the floating point
number.
default precision is six digits after the decimal 
point.
3. fill() :
specifies the character for filling up the unused portion of
field.
it is used with width(). 
4. setf() :
 The function specifies format flags that control output display like left (or) right or right
justification, padding, scientific notation, displaying base number. 
 It provides undo operation for the above mentioned operations. 
Manipulators are special functions for formatting. 
The choice between manipulators and ios functions to solve formatting problems
sometimes depends on the preference of the user. 

5. unsetf():

MANIPULATORS:

Manipulators:

setw()

 

setprecison()

 

setfill()

 

setiosflags()

80

www.cseitquestions.in

resetiosflags() Characteristics of manipulators:

Writing our own manipulators is possible.

Manipulators are easy to write and produce more readable codes and make the

program short.

They need iostream.h and iomanip.h files.

  Some manipulators are needed in pairs to produce the toggle effect.  
Some manipulators are needed in pairs to produce the toggle effect. 
 They are non-member-functions.
Characteristics of ios functions:
 They are single and cannot be combined to have multiple effects. 
They need iostream.h file 
 ios functions are member functions.
The functions do not return the previous status. 
3.4 GENERIC PROGRAMMING:
C++ .it means to write programs that are evaluated at compile time.

A basic example of generic programming are templates of containers: In a statically

typed language like C++ you would have to declare separate containers that hold integers,

floats, and other types or deal with pointers to void and therefore losing all type information.

Templates which are the C++ way of generic programming leverage this constraint by

letting you define classes where one or more parameters are unspecified at the time you define

the class. When you instance the template later you tell the compiler which type it should use

to create the class out of the template.

When a manipulator does not take any arguments , it is passed without the () parenthesis.

Generic programming means that you are not writing source code that is compiled as-is but that yo collection of other objects. But there's much more to generic programming. In the context of

Example: template<typename T> class MyContainer

{

// Container that deals with an arbitrary type T

81

www.cseitquestions.in

};

void main()

{

// Make MyContainer take just ints. MyContainer<int> intContainer;

}

3.5 TEMPLATES:  A significant benefit of object oriented programming is reusability of code which
3.5 TEMPLATES:
 A significant benefit of object oriented programming is reusability of code which 
eliminates redundant coding.
A template allows the construction of family of functions and classes to perform the 
same operation on different types.
There are two types of templates. 
Function templates 
 Class templates 
Templates are used to achieve reusability which eliminates redundant code. 

3.6 CLASS TEMPLATES:

Class templates are used to create generic class witch support different data types.

Syntax:

An important feature of oops called Templates makes this benefit stronger and provides the greater flexibility to the languages.

This provides the generic programming which allows developing the reusable software component such as classes and function.

Terms which means use the same function or class for different purpose without changing their basic meaning where the function or class should be defined only once.

template <class T> class <class_name>

{

Member;

Member function;

};

82

www.cseitquestions.in

Example:

#include<iostream.h>

#include<conio.h>

template <class

T> class complex

{

T real, image; public: void getdata() { cout<<"\n Enter the complex values";
T real, image;
public:
void getdata()
{
cout<<"\n Enter the complex
values"; cin>>real>>image;
}
void putdata()
{
if(image>0)
cout<<real<<"+"<<image<<"i";PLUS.
else cout<<real<<image<"i";
}
}
;
void main()
{
clrscr();
complex <int> obj1;
obj1.getdata();

obj1.putdata();

complex <float>

obj2; obj2.getdata();

obj2.putdata();

getch();

}

83

www.cseitquestions.in

3.7 FUNCTION TEMPLATES:

The template declared for function is function template. Function templates are generic

function, which work for any data that is passed to them. The data type is not specified while

declaring the function. It performs appropriate operation depending on the data type we

passed to them.

Syntax:

Template<typename T ,….> Return Type Function-name(argument) { Function body } Example: Template <
Template<typename T ,….>
Return Type Function-name(argument)
{
Function body
}
Example:
Template < class T>
void generic Bubblesort(T Temp GenericArray[]) // template function
1 {
for( int i=0;i<5; i++)
{
for( int j=i+1;j<5;j++)
{
if(TempGenericArray[i]<TempGenericArray[j])
{
int temp=TempGenericArray[i];
}

TempGenericArray[i]=TempGenericArray[j];

TempGenericArray[j]=temp;

}

Template <class T>

void Generic Display(T TempGenericArray[]) // template function2

{

cout<<“\n”;

for(int i=0;i<5;i++)

{

84

www.cseitquestions.in

cout<<TempGenericArray[i]<<“\t”;

}

}

void main()

{

int Array1[]={1,4,6,2,6}; GenericBubbleSort(Array 1);

//calling function template 1

GenericDisplay(Array2); // calling function template 2 Char Array2[]=“sdfla”; GenaricBubbleSort(Array2) //calling
GenericDisplay(Array2);
// calling function template 2
Char Array2[]=“sdfla”;
GenaricBubbleSort(Array2)
//calling function template 1
Generic Display(Array 2);
Foat Array3[]={ 7.0,9.4,5.2,2.5,0.5);
GenericBubble Sort (Array 3);
// calling function template 1
GenericBubbleSort( Array3 );
// calling function template 2
}
6
4
2
1
k
f
d
a
7
5.2
2.5
0.5
Function templates can have different data type to represent the parameters.
template <class T1, class T2>
return_type function_name(arguments)
{

Sample output:

6

s

9.4