You are on page 1of 49

II YEAR / IV SEMESTER

(ELECTRICAL AND ELECTRONICS ENGINEERING)


CS6456 - OBJECT ORIENTED PROGRAMMING
UNIT - II
BASIC CHARACTERISTICS OF OOP

COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)

VERIFIED BY

HOD

PRINCIPAL

CORRESPONDENT

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


1

SENGUNTHAR COLLEGE OF ENGINEERING TIRUCHENGODE


UNIT II
BASIC CHARACTERISTICS OF OOP

Data Hiding and Member Functions


Object Creation and Destruction
Polymorphism data abstraction
Iterators and Containers

LIST OF IMPORTANT QUESTIONS


UNIT II
BASIC CHARACTERISTICS OF OOP
PART-A
1. What is meant by data abstraction? [A/M2015] [M/J2013] [M/J2012] [N/D2013]
2. What is the use of destructor? [M/J2016] [OR] What is destructor? Illustrate with an
example. [A/M2015]
3. How are inline members functions defined outside the body of the class? Give an
example. [M/J2014]
4. Mention the types of polymorphism in C++. [M/J2014]
5. Define polymorphism. [N/D2014]
6. What are the Access Specifiers used in a class? [N/D2014]
7. Define the term data hiding. [M/J2013]
8. What is constructor? [M/J2012]
9. What is the general form of a class definition in C ++?
10. List out the important characteristics of constructor [N/D2012]

PART-B
1. Explain the various types of constructors that are available in C++ with suitable
example. (16m) [M/J2016] [8m] [A/M2015](16m)[M/J2012] (4m)[A/M2011] [or]
Describe the special characteristics of constructor function. (8m)[N/D2014] [or] Discuss
on Destructor.(4m) [M/J2013] (8m)[N/D2012] (8m)[N/D2011]
2. What is meant by polymorphism? Explain the various types of polymorphism in C++
with suitable examples. (16m) [A/M2015] (6m) [N/D2014] (4m) [M/J2013] (16m)
[N/D2013] (8m)[N/D2011] [or] What is meant by function overloading? Write a C++
program to illustrate the concept of function overloading. (16m)[M/J2012] (8m)
[N/D2012]

3. What is data hiding? What are the different mechanisms for protecting data from the
external uses of a classs objects? (16m) [M/J2014] (8m) [N/D2013]
4. Write short notes about iterators and containers. (8m)[N/D2014] (4m)[M/J2013] (8m)
[N/D2012] (8m) [N/D2013] (8m) [N/D2012] [or] Explain about object creation and
Iterators with example. (16m) [M/J2013]
5. Write a C++ program illustrating class declaration, definition and accessing class
members. (16m) [M/J2014]
6. Write a program to create a class employee with necessary data members and
methods. Create an array of objectives for employee class and print the pay slip for
employees. (10m) [N/D2014]
7. Explain array of objects with example in c++. [M/J2016] [8]
8. What is operator overloading in c++ ? List out the rules to overload a binary operator
[M/J2016][7]
9. Write a C++ program to add two vectors using + operators overloading.[M/J2016]
[9m]

NOTES
UNIT II
BASIC CHARACTERISTICS OF OOP

PART A
1. What is meant by data abstraction? [A/M2015] [M/J2013] [M/J2012] [N/D2013]
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, wait, and cost, and function operate
on these attributes. They encapsulate all the essential properties of the object that are
to be created.
2. What is the use of destructor ? [M/J2016] [OR] What is destructor? Illustrate
with an example. [A/M2015]

Destructor is used to destroy the objects that have been created by a constructor.
It is a member function, whose name is same as the class name preceded by a

tilde.
The destructor never takes any arguments nor does it return any value.
It will be invoked implicitly by the compiler upon exit from the program to clean up

storage.
E.g., ~integer ( ) { }

3. How are inline members functions defined outside the body of the class? Give
an example. [M/J2014]
The member function defined outside the class can be made inline by prefixing
the keyword inline to function declaration as shown below, example of an inline member
function defined outside the class body:
class Foo {
public:
5

void method(); // Best practice: Don't put the inline keyword here
// ...
};
inline void Foo::method() // Best practice: Put the inline keyword here
{
// ...
}
These are the functions designed to speed up program execution. An inline function is
expanded (i.e. the function code is replaced when a call to the inline function is made) in
the line where it is invoked.
4. Mention the types of polymorphism in C++. [M/J2014]

5. Define polymorphism. [N/D2014]


Polymorphism means one name multiple forms (i.e )giving different meanings to
the same function name or operator, dependent on context. The appropriate meaning is
selected on the basis of the type of data being processed.
6. What are the Access Specifiers used in a class? [N/D2014]
A member (either data member or member function) of a class is protected from
direct access is known as access specifier. It of three types are public, private, and
protected.

A member (either data member or member function) declared in a private


section of a class can only be accessed by member functions and friends of that
class.
6

A member (either data member or member function) declared in a protected


section of a class can only be accessed by member functions and friends of that

class, and by member functions and friends of derived classes.


A member (either data member or member function) declared in a public
section of a class can be accessed by anyone.

7. Define the term data hiding. [M/J2013]


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data
is not accessible to the outside world, and only those functions which are wrapped in
the class can access it. These functions provide the interface between the objects data
and the program. This insulation of the data from direct access by the program is called
data hiding or information hiding.
8. What is constructor? [M/J2012]
Constructor is a special member function whose task is to initialize the objects of
its class. It is special because its name is the same as the class name. The constructor
is invoked whenever an object is created.
Class rectangle
{
public:
rectangle ()//constructor definition
{

//displayed whenever an object is created

// Body of the constructor

}
};
9. What is the general form of a class definition in C ++?
Class class_name
{
Private:
7

Variable declaration;
Function declaration;
Public:
Variable declarations;
Function declarations;
};
10. List out the important characteristics of constructor [N/D2012]
The constructor functions have some special characteristics. These are:

They should be declared in the public section.


They are invoked automatically when the objects are created.
They do not have return types, not even void and therefore, and they cannot

return values.
They cannot be inherited, though a derived class can call the base class

constructor.
Like other C++ functions, they can have default arguments.
Constructors cannot be Virtual.
An object with a constructor cannot be used as a member of union.
They make implicit calls to the operators new and delete when memory allocation
is required.

11. Write any four operators that cannot be overloaded. [N/D2012]

Class member access operator (. , .*)


Scope resolution operator (::)
Size operator ( sizeof )
Conditional operator (?:)

12. What is dynamic initialization of objects? [ M/J2007]


Class objects can be initialized dynamically, that is to say, the initial value of an
object may be provided during the run time. One advantage of dynamic initialization is
that we can provide various initialization formats, using overloaded constructors.
13. How the members of a class can be accessed?
8

The private data of a class can be accessed only through the member functions
of that class. The format for calling a member function,
Objectname.function_name(actual _arguments);
14. What are the ways of passing objects as function arguments?
Pass by value: A copy of the entire object is passed to the function. Any changes made
to the object inside the function dont affect the objects used to call the function.
Pass by Reference: Only the address of the object is transferred to the function.
When an address of the object is passed, the called function works directly on the
actual object used in the call. This means that any changes made to the object inside
the function will reflect in the actual object.
15. Give the general form of an operator function.
The general form of an operator function is given as,
return-type class-name :: operator op (arglist)
{
function body
}
Where,
Return-type -> type of value returned
operator -> keyword
op -> operator being overloaded
16. What are reference variable?
A reference variable provides an alias(alternative name) for a previously defined
variable. Sum total For example, if make the variable a reference to the variable, then
sum and total can be used interchangeably to represent that variable.
Syntax:
Data-type &reference-name = variable-name
Eg:
9

float total = 100;


float &sum = total;
17. What do you mean by parameterized constructor?
The data members of objects are initialized with different values when they are
created by passing arguments to the constructor function when they are created. The
constructor that take arguments are called parameterized constructor.
E.g., Class integer
{
int m, n;
public :
integer(int x, int y);
..
..
}
integer :: integer(int x,int y)
{
m=x ;
n=y ;
}
18. What you mean by copy constructor?
A constructor which accepts a reference to its own class as a parameter is called
copy constructor.
Eg:

Class A
{
--------public :
A(A &);
}

19. What are free store operators (or) Memory management operators?

10

New and Delete operators are called as free store operators since they allocate
the memory dynamically.

New operator can be used to create objects of any data type.


Pointer-variable = new data type;

Initialization of the memory using new operator can be done. This can be done
as,
Pointer-variable = new data-type(value)

Delete operator is used to release the memory space for reuse. The general form
of its use is,
Delete pointer-variable;

20. List some of the rules for operator overloading.

Only existing operators can be overloaded.


We cannot change the basic meaning of an operator.
The overloaded operator must have at least one operand.
Overloaded operators follow the syntax rules of the original operators
PART-B

1. Explain the various types of constructors that are available in C++ with suitable
example. (16m) [A/M2015](16m)[M/J2012] (4m)[A/M2011] [or] Describe the
special characteristics of constructor function. (8m)[N/D2014] [or] Discuss on
Destructor.(4m) [M/J2013] (8m)[N/D2012] (8m)[N/D2011]
Constructors(Dynamic initialization of objects)

To initialize a value to the variable, so far we have used the member functions.
By the member functions we cannot initialize a value for the variable at the time

of creation of an object.
Constructor is a special member function whose task is to initialize the objects of

its class. It is special because its name is the same as the class name.
The constructor is invoked whenever an object is created. A Constructor is
defined and declared as follows

The general form is:

Ex:
11

Class classname
{
Datamember declaration;
Public:
Classname()
{

}
Memberfunction definition;
};

class Sum
{
int a,b;
public:
Sum() //constructor definition
{
a=0;
b=0;
}
};
void main()
{
Sum ob; // Creation of object, it calls the
constructor
}

Once the object is created, the constructor will be called automatically, the values
are initialized to the variables. There is no need to write any statement to invoke the
constructor function. A constructor that has no arguments is called the default
constructor.
The constructor functions have some special characteristics. These are:

They should be declared in the public section.


They are invoked automatically when the objects are created.
They do not have return types, not even void and therefore, and they cannot

return values.
They cannot be inherited, though a derived class can call the base class

constructor.
Like other C++ functions, they can have default arguments.
Constructors cannot be Virtual.
An object with a constructor cannot be used as a member of union.
They make implicit calls to the operators new and delete when memory allocation
is required.

Constructors are classified into three types they are as follows


1. Default constructor
2. Parameterized constructor
3. Copy constructor
12

Default constructor [A/M2011]


A constructor that has no arguments is called the default constructor.
Ex:
class Sum
{
int a,b;
public:
Sum() //constructor definition
{
a=0;
b=0;
}
};
void main()
{
Sum ob; // Creation of object, it calls the constructor
}
Once the object is created, the constructor will be called automatically, the values are
initialized to the variables. There is no need to write any statement to invoke the
constructor function. A constructor that has no arguments is called the default
constructor.
Parameterized constructor
It may be necessary to initialize the various data elements of the different objects
with different values when they are created. It can be achieve by passing the arguments
to the constructor function when the objects are created. The constructor that can take
arguments are called parameterized constructor.
Ex:
class sample
{
int a,b;
public:
sample(int x, int y)
{
A=x;
B=y;
}
};

13

When a constructor has been parameterized, the object declaration statement


such as sample s; may not work. We must pass the initial values as initial arguments to
the constructor function when an object is declared.
This can be done in two ways:

By calling the constructor explicitly


By calling the constructor implicitly

Explicit Call:
sample s=sample(10,20);
Implicit call:
sample s(10,20);
Ex:
class sample
{
int a,b;
public:
sample(int x,int y)
{
a=x;
b=y;
}

void disp()
{
int c;
c=a+b;
cout<<c;
}
};
Void main()
{
sample s(10,20);
s.disp();
}

Copy Constructor
A copy constructor is used to declare and initialize an object from another object. For
ex, the statement Sample ob(ob1); would define the object ob and at the same time
initialize it to the values of ob1. Another form of this statement is: sample ob1=ob; this
statement assigns the value of ob to ob1. This is the task of overloaded assignment
operator.

Ex:
class sample

void main()
{
14

{
int a,b,c;
public:
sample()
{
a=10;
b=20;
}
void disp()
{
c=a+b;
cout<<c<<"\n";
}
};

clrscr();
sample ob;
ob.disp();
sample ob1=ob;
ob1.disp();
getch();
}

Destructors

It is used to destroy the objects that have been created by a constructor. Like
constructor, the destructor is also a member function whose name is the same as
the class name but is preceded by the tilde. For ex, the destructor for the class
sample can be defined as shown below:

Characteristics of Destructors

A destructor never takes any argument nor does it return any value.
It will be invoked automatically by the compiler upon exit from the program.
A destructor is used to clean up storage that is no longer accessible.

The general form is:


~sample()
{
}

15

Ex:

~sample()

class sample

cout<<"Objects destroyed:"<<a<<"\n";

public:

sample()

};

void main()

a++;

cout<<"No of objects created:"<<a<<"\n";

clrscr();

sample ob,ob1,ob2,ob3;
getch();
}

2. What is meant by polymorphism? Explain the various types of polymorphism


in C++ with suitable examples. (16m) [A/M2015] (6m) [N/D2014] (4m) [M/J2013]
(16m) [N/D2013] (8m)[N/D2011] [or] What is meant by function overloading?
Write a C++ program to illustrate the concept of function overloading. (16m)
[M/J2012] (8m)[N/D2012]
Polymorphism means one name multiple forms (i.e) giving different meanings
to the same function name or operator, dependent on context. The appropriate meaning
is selected on the basis of the type of data being processed.

16

Static Polymorphism or Compile Time Polymorphism


It means existence of an entity in various physical forms simultaneously. Static
polymorphism refers to the binding of functions on the basis of their signature (number,
type and sequence of parameters). It is also called early binding because the calls are
type and sequence of parameters). It is also called early binding because the calls are
already bound to the proper type of functions during the compilation of the program. For
example,
Void volume (int); //prototype
Void volume (int,int,int); //prototype
When the function volume ( ) is invoked, the passed parameters determine which one to
be executed. This resolution takes place at compile time.
Function overloading

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

A function call first matches the prototype having the same number and type of
arguments and then calls the appropriate function for execution. A best match
must be unique.

The function selection involves the following steps:

The compiler first tries to find an exact match in which the types of actual
arguments are the same, and use that function.

If an exact match is not found, the compiler uses the integral promotions to find
the match.

When either of them fails, the compiler tries to use the implicit conversions to the
actual arguments.

If all of the steps fail, then the compiler will try the user-defined conversions in
combination with integral promotions and built-in conversions to find a unique
match.

17

class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void)
{
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}

When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operators overloading
You can redefine or overload most of the built-in operators available in C++. Thus
a programmer can use operators with user-defined types as well. Overloaded operators
are functions with special names the keyword operator followed by the symbol for the
operator being defined. Like any other function, an overloaded operator has a return
type and a parameter list.

Eg: Box operator+(const Box&);


Operators that are not overloaded are follows
Class member access operator (. , .*)
Scope resolution operator (::)
18

Size operator ( sizeof )


Conditional operator (?:)
Example:
class Cdata
{
private:
int real;
int image;
public:
void getData()
{
cout<<"Get real Part";
cin>>real;
cout<<"Get Imaginary part";
cin>>image;
}
voi disp()
{
cout<<"the complex Number is";
cout<<real<<"+i"<<image<<"\n";
}

Cdata operator +(Cdata C)


{
Cdata T;
T.real=real+C.real;
T.image=image+C.image;
return T;
}
};
void main()
{
Cdata C1,C2,C3;
cout<<"Read first complex Number";
C1.getData();
cout<<"Read Second complex Number";
C2.getData();
C3=C1+C2;
C3.disp();
}

Output:
Read first Complex Number
23
Read Second complex Number
22
The Complex Number is
4+i5
Dynamic Polymorphism or Run-Time Polymorphism

If the appropriate member function could be selected while the program is


running. This is known as run time polymorphism. C++ supports a mechanism
known as virtual function to achieve runtime polymorphism.

19

At runtime, when it is known what class objects are under consideration, the
appropriate version of the function is invoked. Since the functions is linked with a
particular class much later after the compilation, this process is termed as late
binding. It is also known as dynamic binding because the selection of the
appropriate function is done automatically at runtime.

Virtual function

A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create virtual function, precede the functions
declaration in the base class with the keyword virtual. When a class containing
virtual function is inherited, the derived class redefines the virtual function to suit
its own needs.

Base class pointer can point to derived class object. In this case, using base
class pointer if we call some function which is in both classes, then base class
function is invoked. But if we want to invoke derived class function using base
class pointer, it can be achieved by defining the function as virtual in base class,
this is how virtual functions support runtime polymorphism.

Example:
Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};
Class B: public A
{
int b;

B()
{

b = 2;
}
virtual void show()
{
cout <<b;
}

};
int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
20

public:
}
Output is 2 since pA points to object of B and show() is virtual in base class A.
Abstract Class
Abstract Class is a class which contains at least one Pure Virtual function in it.
Abstract classes are used to provide an Interface for its sub classes. Classes inheriting
an Abstract Class must provide definition to the pure virtual function; otherwise they will
also become abstract class.
Characteristics of Abstract Class

Abstract class cannot be instantiated, but pointers and references of Abstract

class type can be created.


Abstract class can have normal functions and variables along with a pure virtual

function.
Abstract classes are mainly used for Up casting, so that its derived classes can

use its interface.


Classes inheriting an Abstract Class must implement all pure virtual functions, or
else they will become Abstract too.

Pure Virtual Functions


Pure virtual Functions are virtual functions with no definition. They start with
virtual keyword and ends with = 0. Here is the syntax for a pure virtual function,
virtual void f() = 0;
Example
class Base

//Abstract base class

int main()

public:

Base obj; //Compile Time Error

virtual void show() = 0;//Pure Virtual Function

Base *b;

};

Derived d;

class Derived:public Base

b = &d;

public:

b->show();

void show()

}
21

{ cout << "Implementation of Virtual


Function in Derived class"; } };

Output : Implementation of Virtual Function in Derived class


In the above example Base class is abstract, with pure virtual show() function, hence
we cannot create object of base class.
3. What is data hiding? What are the different mechanisms for protecting data
from the external uses of a classs objects? (16m) [M/J2014] (8m) [N/D2013]
Data hiding is one of the important features of Object Oriented Programming
which allows preventing the functions of a program to access directly the internal
representation of a class type. The access restriction to the class members is specified
by the labeled public, private, and protected sections within the class body. The
keywords public, private, and protected are called access specifiers.
A class can have multiple public, protected, or private labeled sections. Each
section remains in effect until either another section label or the closing right brace of
the class body is seen. The default access for members and classes is private.
Genral form:
class Base {
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};

22

The public members:


A public member is accessible from anywhere outside the class but within a
program. You can set and get the value of public variables without any member function
as shown in the following example:

Example:
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
double Line::getLength(void)
{
return length ;
}
void Line::setLength( double len )
{
length = len;
}

int main( )
{
Line line;
line.setLength(6.0);
cout << "Length of line : " <<
line.getLength() <<endl;
line.length = 10.0;
cout << "Length of line : " << line.length
<<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Length of line : 6
Length of line : 10
The private members:
A private member variable or function cannot be accessed, or even viewed
from outside the class. Only the class and friend functions can access private members.
By default all the members of a class would be private, for example in the
following class width is a private member, which means until you label a member, it will
be assumed a private member:
23

class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so
that they can be called from outside of the class as shown in the following program.
Example:
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
double Box::getWidth(void)
{
return width ;
}
void Box::setWidth( double wid )
{
width = wid;
}

int main( )
{
Box box;
box.length = 10.0 cout << "Length of
box : " << box.length <<endl;
box.width = 10.0;
box.setWidth(10.0);
cout << "Width of box : " <<
box.getWidth() <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Length of box : 10
Width of box : 10

24

The protected members:


A protected member variable or function is very similar to a private member but
it provided one additional benefit that they can be accessed in child classes which are
called derived classes.
Following example is similar to above example and here width member will be
accessible by any member function of its derived class SmallBox.

Example
class Box
{
protected:
double width;
};
class SmallBox:
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}

int main( )
{
SmallBox box;
box.setSmallWidth(5.0);
cout << "Width of box : "<<
box.getSmallWidth() << endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Width of box : 5

25

4. Write short notes about iterators and containers. (8m)[N/D2014] (4m)[M/J2013]


(8m)[N/D2012] (8m) [N/D2013] (8m) [N/D2012] [or] Explain about object
creation and Iterators with example. (16m) [M/J2013]
Standard Template Library (STL)
A standard template library (STL) is a software library that extends C++
standard library's capabilities and provides a ready-made set of common classes for C+
+, including associative arrays and containers, which are used along with built-in and
user-defined types that support elementary operations.
At the core of the Standard Template Library are three foundational items:

Containers,

Algorithms

Iterators

Containers are objects that hold other objects. There are several different types of
containers. For example, the vector class defines a dynamic array, queue creates a
queue, and list provides a linear list.
Algorithms act on the contents of containers. They include capabilities for initializing,
sorting, searching, and transforming the contents of containers. Many algorithms
operate on a range of elements within a container.
Iterators are objects that act, more or less, like pointers. They give you the ability to
cycle through the contents of a container in much the same way that you would use a
pointer to cycle through an array.
In addition to containers, algorithms, and iterators, the STL relies upon several
other standard components for support. Each container has defined for it an allocator.
Allocators manage memory allocation for a container. The default allocator is an object
of class allocator, but you can define your own allocators if needed by specialized
applications.
The Container Classes
The containers defined by the STL and the headers necessary to use each container
are shown below,

26

Required

Container

Description

bitset
deque
list
map

A set of bits.
A double-ended queue.
A linear list.
Stores key/value pairs in which each key is

multimap

associated with only one value.


Stores key/value pairs in which one key may <map>

Header
<bitset>
<deque>
<list>
<map>

be associated with two or more values.


multiset

A set in which each element is not necessarily <set>

priority_queu

unique.
A priority queue.

<queue>

e
queue
set
stack

A queue.
A set in which each element is unique.
A stack.

<queue>
<set>
<stack>

vector

A dynamic array.

<vector>

Algorithms
Algorithms act on containers. Although each container provides support for its
own basic operations, the standard algorithms provide more extended or complex
actions. To have access to the STL algorithms, you must include <algorithm> in your
program.
Algorithm
adjacent_find

Purpose
Searches for adjacent matching elements within a sequence and

count
count_if

returns an iterator to the first match.


Returns the number of elements in the sequence.
Returns the number of elements in the sequence that satisfy some

find

predicate.
Searches a range for a value and returns an iterator to the first

find_end

occurrence of the element.


Searches a range for a subsequence. It returns an iterator to the end

includes

of the subsequence within the range.


Determines if one sequence includes all of the elements in another
27

lower_bound

sequence.
Finds the first point in the sequence that is not less than a specified

.
max
merge

value
Returns the maximum of two values.
Merges two ordered sequences, placing the result into a third

min
remove, emove_if,

sequence.
Returns the minimum of two values.
Removes elements from a specified range.

remove_copy,and
remove_copy_if
search
set_difference

Searches for subsequence within a sequence.


Produces a sequence that contains the difference between two

set_intersection

ordered sets.
Produces a sequence that contains the intersection of the two

upper_bound

ordered sets.
Finds the last point in a sequence that is not greater than some

partial_sort
partial_sort_copy

value.
Sorts a range.
Sorts a range and then copies as many elements as will fit into a
resulting sequence.

Iterators
Iterators are similar to pointers.
Iterators
Random Access
Bidirectional
Forward
Input
Output

Access Allowed
Store and retrieve values. Elements may be accessed randomly.
Store and retrieve values. Forward and backward moving.
Store and retrieve values. Forward moving only.
Retrieve, but not store values. Forward moving only.
Store, but not retrieve values. Forward moving only.

In general, an iterator that has greater access capabilities can be used in place of
one that has lesser capabilities. For example, a forward iterator can be used in place of
an input iterator. Iterators are handled just like pointers. You can increment and
decrement them. You can apply the * operator to them. Iterators are declared using the
iterator type defined by the various containers.
The STL also supports reverse iterators. Reverse iterators are either
bidirectional or random-access iterators that move through a sequence in the reverse
28

direction. Thus, if a reverse iterator points to the end of a sequence, incrementing that
iterator will cause it to point to one element before the end.
Example:

// access 5 values from the vector

int main()

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

cout << "value of vec [" << i << "] = "


// create a vector to store int

<< vec[i] << endl;

vector<int> vec;

int i;

// use iterator to access the values

// display the original size of vec

vector<int>::iterator v = vec.begin();

cout << "vector size = " << vec.size() <<

while( v != vec.end()) {

endl;

cout << "value of v = " << *v << endl;

// push 5 values into the vector

v++;

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

vec.push_back(i);

return 0;

// display extended size of vec


cout << "extended vector size = " <<
vec.size() << endl;

When the above code is compiled and executed, it produces the following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
29

value of v = 4
5. Write a C++ program illustrating class declaration, definition and accessing
class members. (16m) [M/J2014]
Class
The classes are the most important feature of C++ that leads to Object Oriented
programming. Class is a user defined data type, which holds its own data members and
member functions, which can be accessed and used by creating instance of that class.
The variables inside class definition are called as data members and the functions are
called member functions.
Class of birds, all birds can fly and they all have wings and beaks. So here flying
is a behavior and wings and beaks are part of their characteristics. And there are many
different birds in this class with different names but they all posses this behavior and
characteristics.
Example, class Study
Objects
Class is mere a blueprint or a template. No storage is assigned when we define a
class. Objects are instances of class, which holds the data variables declared in class
and the member functions work on these class objects.
Example, Study obj;
Defining Class and Declaring Objects
When we define any class, we are not defining any data, we just define a
structure or a blueprint, as to what the object of that class type will contain and what
operations can be performed on that object.
Syntax of class definition,
class ClassName

Example:

class Student

Access specifier:

Data members;

public:

30

Member Functions()

int rollno;

string name;

}A,B;

};
Here A and B are the objects of class Student, declared with the class
definition. We can also declare objects separately, like we declare variable of primitive
data types. In this case the data type is the class name, and variable is the object.
int main()
{
Student A;
Student B;
}
Both A and B will have their own copies of data members.
Accessing Data Members of Class
Accessing a data member depends solely on the access control of that data
member. If its public, then the data member can be easily accessed using the direct
member access (.) operator with the object of that class. If, the data member is defined
as private or protected, then we cannot access the data variables directly. Access
specifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,
1 public
2 private
3 protected
Public
Public, means all the class members declared under public will be available to
everyone. The data members and member functions declared public can be accessed

31

by other classes too. Hence there are chances that they might change them. So the key
members must not be declared public.
class PublicAccess
{
public: // public access specifier
int x;

// Data Member Declaration

void display(); // Member Function decaration


}
Private
Private keyword, means that no one can access the class members declared
private outside that class. If someone tries to access the private member, they will get a
compile time error. By default class variables and member functions are private.
class PrivateAccess
{
private: // private access specifier
int x;

// Data Member Declaration

void display(); // Member Function decaration


}
Protected
Protected, is the last access specifier, and it is similar to private, it makes class
member inaccessible outside the class. But they can be accessed by any subclass of
that class. (If class A is inherited by class B, then class B is subclass of class A. We will
learn this later.)
class ProtectedAccess
{
protected: // protected access specifier
int x;

// Data Member Declaration

void display(); // Member Function decaration


}

32

6. Write a program to create a class employee with necessary data members


and methods. Create an array of objectives for employee class and print the
pay slip for employees. (10m) [N/D2014]
class employee

void employee :: print()

private :

int empno;

cout<<"Emp No. :"<<empno<<"\n";

char name[20];

cout<<"Name

float basic,da,it,net_sal,gross_sal;

cout<<"basic :"<<basic<<"\n";

public :

cout<<"Net salary

:"<<name<<"\n";
:"<<net_sal<<"\n";

void read();
void cal();

void print();

void main()

};

void employee :: read()

employee e[10];

int i ,n;

cout<<"Enter the emp no. :";

clrscr();

cin>>empno;

cout<<"Enter the no. of employee :";

cout<<"Enter the name of the employee

cin>>n;

:";

for(i=0;i<n;i++)

cin>>name;

cout<<"Enter the basic salary of the

e[i].read();

employee :";

e[i].cal();

cin>>basic;

for(i=0;i<n;i++)

void employee :: cal()

e[i].print();

getch();

da=basic*.52;

gross_sal=basic+da;
it=gross_sal*.30;
net_sal=gross_sal-it;
33

Output:
Enter the no. of employee :2
Enter the emp no. :1
Enter the name of the employee :alok
Enter the basic salary of the employee :6000
Enter the emp no. :2
Enter the name of the employee :pravin
Enter the basic salary of the employee :7000
Emp No. :1
Name

:alok

basic :6000
Net salary

:6384

Emp No. :2
Name

:pravin

basic :7000
Net salary

:7448

7. Explain array of objects with example in c++.[M/J2016] [8]


Like array of other user-defined data types, an array of type class can also be created.
The array of type class contains the objects of the class as its individual elements.
Thus, an array of a class type is also known as an array of objects. An array of objects
is declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is
class_name array_name [size] ;

To understand the concept of an array of objects, consider this example.


Example : A program to demonstrate the concept of array of objects
#include<iostream>
using namespace std;
class books
{
34

char tit1e [30];


float price ;
public:
void getdata ();
void putdata ();
};
void books :: getdata ()
{
cout<<"Title:;
Cin>>title;
cout<<"Price:;
cin>>price;

}
void books :: putdata ()
{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n;
const int size=3 ;
int main ()
{
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details o book "<<(i+1)<<"\n";
35

book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\nBook "<<(i+l)<<"\n";
book[i].putdata() ;
}
return 0;
}

The output of the program is

Enter details of book 1


Title: c++
Price: 325
Enter details of book 2
Title: DBMS
Price:. 455
Enter details of book 3
Title: Java
Price: 255
Book 1
Title: c++
Price: 325
Book 2
36

Title: DBMS
Price: 455
Book 3
Title: Java
Price: 255
In this example, an array book of the type class books and size three is declared. This
implies that book is an array of three objects of the class books. Note that every object
in the array book can access public members of the class in the same way as any other
object, that is, by using the dot operator. For example, the statement book [i] . getdata ()
invokes the getdata () function for the ith element of array book.
When an array of objects is declared, the memory is allocated in the same way as to
multidimensional arrays. For example, for the array book, a separate copy of title and
price is created for each member book[0], book[l] and book[2]. However, member
functions are stored at a different place in memory and shared among all the array
members. For instance, the memory space is allocated to the array of objects book of
the class books.

8. What is operator overloading in c++ ? List out the rules to overload a binary
operator [M/J2016][7]
Operators overloading in C++
We can redefine or overload most of the built-in operators available in C++. Thus a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed
by the symbol for the operator being defined. Like any other function, an overloaded
operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final
Box object. Most overloaded operators may be defined as ordinary non-member
functions or as class member functions. In case we define above function as nonmember function of a class then we would have to pass two arguments for each
operand as follows:
Box operator+(const Box&, const Box&);

37

Rules for operator overloading


In C++, following are the general rules for operator overloading.
1) Only built-in operators can be overloaded. New operators can not be created.
2) Arity of the operators cannot be changed.
3) Precedence and associativity of the operators cannot be changed.
4) Overloaded operators cannot have default arguments except the function call
operator () which can have default arguments.
5) Operators cannot be overloaded for built in types only. At least one operand must be
used defined type.
6) Assignment (=), subscript ([]), function call (()), and member selection (->) operators
must be defined as member functions
7) Except the operators specified in point 6, all other operators can be either member
functions or a non member functions.
8 ) Some operators like (assignment)=, (address)& and comma (,) are by default
overloaded.

9. Write a C++ program to add two vectors using + operators overloading.


[M/J2016] [9m]
C++ incorporates the option to use language standard operators between classes in
addition to between fundamental types. For example:
int a, b, c;
a = b + c;
is perfectly valid, since the different variables of the addition are all fundamental
types. Nevertheless, is not so obvious that we can perform the following operation (in
fact it is incorrect):
struct { char product [50]; float price; } a, b, c;
a = b + c;
The assignation of a class (or struct) to another one of the same type is allowed
(default copy constructor). What would produce an error would be the addition
operation, that in principle is not valid between non-fundamental types.
But thanks to the C++ ability to overload operators, we can get to do that.
Objects derived from composed types such as the previous one can accept operators
38

which would not be accepted otherwise, and we can even modify the effect of operators
that they already admit. Here is a list of all the operators that can be overloaded:

<

>

+= -= *= /= << >>

<<= >>= == != <= >= ++ -- %


~

&

&= ^= |= && || %= [] () new delete

To overload an operator we only need to write a class member function whose


name is operator followed by the operator sign that we want to overload, following this
prototype:

type operator sign (parameters);

Here we have an example that includes the operator +. We are going to sum the
bidimensional vectors a(3,1) and b(1,2). The addition of two bidimensional vectors is an
operation as simple as adding the two x coordinates to obtain the resulting x coordinate
and adding the two y coordinates to obtain the resulting y. In this case the result will be
(3+1,1+2) = (4,3).

// vectors: overloading operators example


#include <iostream.h>

class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
39

};

CVector::CVector (int a, int b) {


x = a;
y = b;
}

CVector CVector::operator+ (CVector param) {


CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}

int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}

4,3

40

If you are baffled seeing CVector so many times, consider that some of them make
reference to the class name CVector and others are functions with that name. Do not
confuse them:

CVector (int, int);

// function name CVector (constructor)

CVector operator+ (CVector); // function operator+ that returns CVector type

The function operator+ of class CVector is the one that is in charge of overloading the
arithmetic operator +. This one can be called by any of these two ways:

c = a + b;
c = a.operator+ (b);

Notice also that we have incuded the empty constructor (without parameters) and we
have defined it with a no-op block of instructions:

CVector () { };

this is necessary, since there already exists another constructor,

CVector (int, int);

so none of the default constructors will exist in CVector if we do not explicitly declare
one as we have done. Otherwise the declaration

CVector c;

41

included in main() would not be valid.

Anyway, I have to warn that a no-op block is not a recommended implementation for a
constructor, since it does not fulfill the minimum functionality that a constructor should
have, which is the initialization of all the variables in the class. In our case this
constructor leaves variables x and y undefined. Therefore, a more advisable declaration
would have been something similar to this:

CVector ()
{
x=0;
y=0;
};

that for simplicity I have not included in the code.


10. Write a c++ program to illustrate the working of static function in c++ [N/D2012]
Static data members
A data member of a class can be qualified as static. A static variable has
certain special characteristics. They are:

It is initialized to zero when the first object of its class is created. No other
initialization is permitted.

Only one copy of that member is created for the entire class and is shared by all
the objects of that class, no matter how many objects are created.

It is visible only within the class, but its lifetime is the entire program.
the this pointer.

Since a static member is independent of a particular instance, it can be accessed in the


form
class-name :: identifier

42

Note the use of the scope resolution operator. A static member of a global class must be
explicitly declared and defined in file scope
Example:
class item
{
static int count;
public:
void get()
{
count++;
}
void put()
{
cout<<"Count"<<count<<"\n";
}
};
int item::count;
//definition of the static
data member

void main()
{
item ob,ob1,ob2;
clrscr();
ob.get();
ob1.get();
ob2.put();
ob2.get();
ob.put();
ob1.put();
ob2.put();
getch();
}

Note that the type and scope of each static member variable must be defined outside
the class definition. This is necessary because the static data members are stored
separately.
Static member functions [A/M2011]
Like static variable, we can also have static member functions. A member
function that is declared static has the property that a static function can have access to
only other static members (functions or variables) declared in the same class.
It has some restrictions:

They do not possess this pointer because they are not member functions.

They cannot access other data member of the class because doing so it will
implicitly call the this pointer.

They cannot be Virtual.

They cannot be declared either const or volatile.

A static member function can be called using the class name instead of its objects as
follows:
43

class-name :: function-name();
Example:
class item
{
static int count;
public:
void get()
{
count++;
}
static void put()
{
cout<<"Count"<<count<<"\n";
}
};

int item::count;
//definition of the static data
member
void main()
{
item ob,ob1,ob2;
clrscr();
ob.get();
ob1.get();
item::put(); // definition of the static member
function
ob2.get();
item::put();
getch();
}

11. Illustrate about nested classes with sample program [N/D2011]


Nested Classes
It is possible to define a class inside another class. This is said to be nested
class. Like blocks and namespaces, classes are scopes and can nest. Nesting allows
local hiding of names and local allocation of resources. This is often desirable when a
class is needed as part of the implementation of a larger construct. The member
functions must be defined inside the local class and cannot be referred to outside this
scope.
Example:
class outer

b=10;

int b;

int c=ob.a+b; //

public:

cout<<c;

class inner

};

public:

void main()

int a;

{
44

void ass()

clrscr();

outer ob1;

a=10;

outer::inner ob;

ob.ass(); //call the function defined in inner

};

class

void add(inner ob) //function definition in ob1.add(ob); // call the function defined in
outer class with inner class object as outer class
argument

getch();
}

In this example, we define the class inner inside the class outer in public section. The
statement outer ob1 will create an object for the outer class. Outer::inner ob will create
an object for the class inner.
9. Explain about member functions in detail.
Member Functions
C++ allows functions to be members. C allows only data members. The function
declaration is included in the structure declaration. The idea is that the functionality
required by the structure or class should often be directly included in the class or struct
declaration. Such functions are called class methods. This term method, meaning
member function, comes from object-oriented programming methodology.
Defining member functions
Member functions can be defined in two places;

Inside the class definition

Outside the class definition

Inside the class definition

Outside the class definition

Syntax:

A function can be defined outside the

Class class_name
{
Data members;

class,
Syntax:
45

return-type Function_name(arguments)
{

return-type class-name::functionname(arguments)

Body of the function

Body of the function

Example:

class Sum

Example:

class Sum

private:

{
int a,b,c;

private:

public:

int a,b,c;

void get() // Functions defined inside the

public:

class

void get(); // Functions declaration

};

};

a=10;

void Sum::get() //function defined outside

b=20;

the class

c=a+b;

cout<<Sum is<<c;

a=10;

b=20;
c=a+b;
cout<<Sum is<<c;
}

The membership label class-name :: tells the compiler that the function
function-name belongs to the class class-name. that is the scope of the function is
restricted to the class-name specified in the header line. The symbol :: is called the
scope resolution operator. Since the functions do not return any value, their return type
is void.

The member functions have some special characteristics, they are:


46

Several different classes can use the same function name. The memebership
label will resolve their scope.

Member functions can access the private data of the class. A non member
function cannot do so.

A member function can call another member function directly.

Scope resolution operator in c++


Scope resolution operator(::) is used to define a function outside a class or
when we want to use a global variable but also has a local variable with same name.
Example:
char c = 'a';

// global variable

int main() {
char c = 'b'; //local variable
cout << "Local variable: " << c << "\n";
cout << "Global variable: " << ::c << "\n"; //using scope resolution operator
return 0;
}
Output:
Local variable: b
Global variable: a
Scope resolution operator in class
class programming
{
public:
void output(); //function declaration
};
// function definition outside the class
void programming::output() {
cout << "Function defined outside the class.\n";
}
47

int main() {
programming x;
x.output();
return 0;
}
Output:
Function defined outside the class.
10. Write a program to perform the following using Function Overloading [N/D2012]
(i)To read a set of integers
(ii)To read a set of floating point numbers
(iii) To read a set of double numbers and Find out the Average.
void average(int,int);
void average(float,float);
void add(double,double);
class Sum
{
int a,b,c;
float d,e,f,avg;
double g,h,i;
public:
void average()
{
a=10;
b=20;
c=a+b;
avg=c/2;
cout<< the average of integer nos is <<avg<<"\n";
}
void average(float x,float y)
48

{
d=x;
e=y;
f=d+e;
avg=f/2;
cout<< the average of float nos is <<avg<<"\n";
}
void average(double p,double q)
{
g=p;
h=q;
i=g+q;
avg=i/2;
cout<< the average of double nos is <<avg<<"\n";
}
};
void main()
{
Sum ob;
clrscr();
ob.average(30,20);
ob.average(20.3f,20.2f);
ob.average(10.5d,11.5d);
getch();
}

49