You are on page 1of 46

1

www.nskinfo.com- College Student and Faculty Website


Department Of nskinfo i-education
www.nsksofttech.com- AnnaUniversity Chennai all department soft copy question
paper& More than 500 c&c++ programs coming soon.

CS2203-Object Oriented Programming Paradigm-16MARKS
ANSWERS

Unit - I
1. Discuss in detail about the Concepts of the OOPS
The basic concepts of OOPS are,
Objects:
An instance of a class is known as an Object. Object is an runtime
entities. It represents a bank, a person or any item that the program has handle.
Objects may also user defined. Each object ncan interact with other by sending
messages. Objects can having the code.
OBJECT
STUDENT
DATA
NAME
MARKS
FUNCTION
TOTAL

Classes:
A Class is a collection of objects of similar type.
Syntax:
Class class-name;
Example:
Class mango;
Where mango is the name of the class.
Data Abstraction and Encapsulation:
The wrapping up of the data and functions into a single unit is known
as encapsulation. The insulation of data from direct access by the program is
called data hiding.


2
Abstraction refers to the act or representing essential features without
including the background details. The attributes are sometimes called as data
members and functions that operating on that data is called member
function. A class using the data abstraction concept is known as Abstract
Data Type (ADT).
I nheritance:
Inheritance is the process by which objects acquiring the properties
of the object of another class. The important property of inheritance is
Reusability. Also define as Inheritance is a mechanism of deriving a new
class from an old class. Here we say new class as derived Class and an Old
Class as Base Class.
Polymorphism:
It is a Greek term, means ability to take more than one form. An
operation may exhibit different behaviors in different instances. There are
two types of polymorphism. They are, operator overloading and function
overloading. The process of making an operator to exhibit different behavior
in different instances is operator overloading. The process of making a
function to exhibit different behavior in different instances is function
overloading.
Dynamic Binding:
Binding refers to the linking of the procedure call to the code to be
executed in response to the call. Dynamic (Late) Binding means that the
code associated with the given procedure call isnt known until the time or
the call at runtime.
Message Passing:
Message Passing is the process of communication between the objects.
Creating classes that defines objects and their behavior.
Creating object from class.
Establishing communication among objects.
Message for an object is a request for execution of a procedure and
therefore it will invoke a function. Message passing involves specifying the
name of the object, name of the function and information to be sent.
Example: Employee. Salary (name);
Where employee is the object, salary is the function and the name is the
information.

2. Write a C++ program using inline function
Inline function is expanded in line when it is invoked. The compiler replaces the
function call with the corresponding function code.
Syntax:
1. datatype function(parameters) { statements; }
2. inline datatype class::function (parameters) { statements; }


3
The first syntax example declares an inline function by default. The syntax must
occur within a class definition.
The second syntax example declares an inline function explicitly. Such
definitions do not have to fall within the class definition.

Samples:
/* First example: Implicit inline statement */
int num; // global num
class cat
{
public:
char* func(void) { return num; }
char* num;
}
/* Second example: Explicit inline statement */
inline char* cat::func(void) { return num; }
Program to define function cube ( ) as inline for calculating cube:
void main ( )
{
clrscr ( );
int cube (int);
int j, k, v = 5;
j = cube (3);
k = cube (v);
cout << \n Cube of J = <<j;
cout << \n Cube of K = <<k;
}
inline int cube (int h)
{
return (h*h*h);
}
Output:

Cube of J = 27
Cube of K = 125

3. Explain briefly about function overloading with a suitable example and also its
principles.
Same function name for a number of times for different purposes. Defining multiple
functions with same is function overloading.

Example:



4
int sqr (int);
float sqr (float);
int main ( )
{
int a = 15;
float b = 2.5;
cout <<Square = << sqr (a) << \n;
cout <<Square = << sqr (b) << \n;
return 0;
}
int sqr (int s)
{
Return (s * s);
}
float sqr (float j)
{
Return (j * j);
}

Output:

Square = 225
Square = 6.25

Principles:

If two functions have similar type of data type and arguments function cant be
overloaded.
Passing constant values directly instead of variable also results in ambiguity.
To overcome this declares the prototype declaration of all overloaded function
before main ( ) function and also pass variable as an argument instead of
values.

4. Explain Local Class and Nested Class with an example

Local Class:
Classes can be defined and used inside a function or a block; such classes
are called Local Classes.
Local class can use global variable and static variable declaration inside
the function. Global variable should be used with Scope Operator (::).
Example:
Class A
{
private:
int a;



5
public:
void get()
{
cout<<\n Enter the value for a:;
cin >>a;
}
void show()
{ cout<<endl<<a = <<a; }
};
int main()
{
clrscr();
class B
{
int b;
public:
void get()
{
cout<<\n Enter the value for b:;
cin >>b;
}
void show()
{
cout<<endl<<b = <<b;
}
};
A j; B k;
j.get(); k.get();
j.show(); k.show();
return 0;
}





6
Output:

Enter the value for a: 3
a = 3
Enter the value for b: 5
b = 5
Nested Class:
Inheriting one class into other class. In the nested class the member object
are created using their respective constructors and then the other ordinary
members are created.
All objects of one class will contain the objects of another class. This kind
of relation is called containership or nesting.
Nested object can be created by two stages. First the member object is
created using their respective constructors and then the other ordinary
members are created.
Example:
Class gamma
{
alpha a; // a is an object of alpha class
beta b; // b is an object of beta class
public:
gamma (arglist) : a (arglist1), b (arglist2)
{
// Constructor
}
};
gamma (int x, int y, int z) : a (x), b (x,z)

5. Explain Friend Function and its with suitable example and also its
characteristics.
A function that is declared with a keyword friend is known as friend function. A
function can be declared as a friend in any number of classes.
Friend function must be preceded with a keyword friend.
The function defined elsewhere in the program like normal C++ function.
Function definition doesnt use either keyword friend or scope resolution
operator.
Friend function although not a member function, it has full rights to access the
private members of a class



7
Declaration:

Class class-name
{
Public:
..
Friend void xyz (void);
};

Example:

#include <iostream.h>
class sample
{
int a, b;
public:

void setvalue( )
{
a=25; b=40;
}
friend float mean (sample s);
};
float mean (sample s)
{
return float (s.a + s.b) / 2.0;
}
int main ( )
{
sample x;
x.setvalue ( );
cout << Mean value = << mean (x) << \n;
return 0;
}

Output:

Mean Value = 32.5

Characterstics:

Its not in the scope of the class to which it has been declared as friend.
Since it is not in the scope of the class it cant be called using object of that class.
It can be invoked like a normal function without help of any object.
It can be declared either in public or private part of the class.
It has object as argument.
Often used in operator overloading.

Unit II


8

1. Explain Constructor with suitable example. Discuss any two types of
Constructors with suitable example.
A constructor is a special member function whose task is to initialize the
objects of its class. It is special because its name is same as class name. The
constructor is invoked whenever an object of its associated class is created. It is
called constructor because it constructs the values of data members of the class

Example:

#include <iostream.h>
class num
{
private:
int a, b, c;
public:
num (void); // Declaration of the Constructor
void show ( )
{
cout <<a=<<a <<b=<<b <<c=<<c;
}
};
num :: num (void) // Definition of the Constructor
{
cout << \n Constructor called";
cout << Enter the values for a, b and c:;
cin >>a >>b >>c;
}
int main ( )
{
clrscr ( );
class num x;
x.show ( );
return 0;
}

Output:

Constructor called
Enter values for a,b and c: 1 5 4
a = 1 b = 5 c = 4
Parameterized Constructor:

Constructor with arguments is called parameterized constructor. To invoke
parameterized constructor we must pass the initial values as arguments to the constructor
function when an object is declared. This is done in two ways,
1. By calling the constructor explicitly
eg: integer int1=integer(10,10);



9
2. By calling the constructor implicitly
eg: Integer int1(10,10);

Example:

#include <iostream.h>
class num
{
private:
int a, b, c;
public:
num (int m, int j, int k); // Parameterized Constructor
void show ( )
{
cout cout <<a=<<a <<b=<<b <<c=<<c;;
}
};
num :: num (int m, int j, int k) // Definition of the Constructor
{
a = m; b = j; c = k;
}
int main ( )
{
clrscr ( );
class num x = num (4,5,7);
class num y(1,2,8);
x.show ( );
y.show ( );
return 0;
}

Output:

a = 4 b = 5 c = 7
a = 1 b = 2 c = 8

Copy Constructor:

Constructor can accept a reference to its own class as a parameter which is known as
copy constructor. All copy constructors require one argument with reference to an object of that
class. When no copy constructor defined then compiler supplies its own copy constructor.




Example:

class num
{
int n;


10
public:
num ( ) { } // Constructor without arguments
num (int k) { n = k; } // Parameterized Constructor
num (num &j) { n = j.n; } // Copy Constructor
void show ( ) { cout <<n; }
};
int main ( )
{
clrscr ( );
num J (50); // object J is created and initialized
num K (J); // Copy constructor called
num L = J; // Copy constructor called again
num M; // M is created but not initialized
M = J; // Copy constructor not called
cout << Object J value:; J.show( );
cout << Object K value:; K.show( );
cout << Object L value:; L.show( );
cout << Object M value:; M.show( );
return 0;
}

Output:

Object J value: 50
Object K value: 50
Object L value: 50
Object M value: 50

2. Explain Operator Overloading with example.
The mechanism of giving such special or additional meaning to an operation to an operation is
known as operator overloading.
Syntax:

Return-type class-name :: operator op (arglist)
{ // Function body; }

Where op is the operator to be overloaded. Operator op is a function name. Operator
function must be either member function or friend function. The difference is friend function
have only one argument for unary operator and two arguments for binary operator but member
function has no argument for unary operator and only one argument for binary operator.

Example: vector operator ( );

Overloading Unary Operator:

Unary minus operations are - , ++, --.
class space


11
{
int x;
int y;
int z;
public:
void getdata (int a, int b, int c);
void display (void);
void operator ( );
};
void space :: getdata (int a, int b, int c)
{
x = a; y = b; z = c;
}
void space :: display (void)
{
cout << x<<y<<z;
}
void space :: operator ( )
{
x = -x; y = -y; z = -z;
}
int main ( )
{
space S;
S.getdata (10, -20,30);
cout<< S :;
S.display ( );
-S;
cout <<S :;
S.display ( );
eturn 0;
}
Output:

S : 10 -20 30
S : -10 20 -30


3. Explain in detail about the Overloading using Friend Functions with example.

The syntax for this is,
Friend return-type operator op (vari1, vari2)
{ // Statements; }


12

Example:

class space
{
int x;
int y;
int z;
public:
void getdata (int a, int b, int c);
void display (void);
friend void operator ( space &s);
};
void space :: getdata (int a, int b, int c)
{
x = a; y = b; z = c;
}
void space :: display (void)
{
cout << x<<y<<z;
}
void space :: operator (space &s )
{
s.x = -s.x; s,y = -s.y; s.z = -s.z;
}
int main ( )
{
space S;
S.getdata (10, -20,30);
cout<< S :;
S.display ( );
-S;
cout <<S :;
S.display ( );
return 0;
}


Output:

S : 10 -20 30
S : -10 20 -30

4. What is the use of Type Conversion? Explain in detail with relevant example.


13

For Basic Type,
int m;
float x = 3.14;
m = x;
Convert x to an int before its value assigned to m. fractional part is truncated.
For User Defined DT conversions can be done as,
a) Conversion from Basic Type to Class Type,
b) Conversion from Class Type to Basic Type,
c) Conversion from Class Type to Class Type.
Basic to Class Type Conversion:

Also can be called as type casting. It can be easily carried out by the compiler
automatically.
In this type the Left hand operand of = sign is always class type and Right Hand
Operand is always basic type.

Program to define constructor with no arguments and with float arguments:

class data
{
int x;
float f;
public:
data ()
{ x = 0; f = 0; }
data (float m)
{ x = 2; f = m; }
void show ()
{
cout<<X = <<x<<F = <<f;
cout<<X = <<x<<F = <<f;
}
};
int main ()
{
clrscr();
data z;
z = 1; // z is a class object & 1 is int basic DT
z.show ();
z = 2.5;
z.show ();
return 0;
}

Output:



14
X = 2 f = 1
X = 2 f = 1
X = 2 f = 2.5
X = 2 f = 2.5

Class to Basic Type Conversion:

In this the constructor has no effect. So the type casting can be used by which the
user cans explicitly telling to the compiler for conversions.
These instructions are written in memory functions.
The compiler first searches for the operator keyword followed by DT. If it is not
found then the compiler applies the conversion function.
In this type the Left hand operand of = sign is always basic type and Right Hand
Operand is always class type.
The syntax is,

operator type name ()
{ function statements; }

Example: operator double { }
To convert class type to basic type following conditions should be satisfied,

Conversion function doesnt have any arguments.
It should be a class member function.

Example:

class data
{
int x;
float f;
public:
data ()
{ x = 0; f = 0; }
operator int ()
{ return x; }
operator float ()
{ return f; }
data ( float m)
{ x = 2; f = m; }


void show ()
{
cout<<X = <<x<<F = <<f;
cout<<X = <<x<<F = <<f;
}
};
int main ()
{


15
clrscr();
int j; float f;
data a;
a = 5.5; // a is a class object & j is int basic DT
j = a; //operator int is executed
f = a; //operator float is executed
cout<< Value of J: <<j;
cout<< Value of F: <<f;
return 0;
}
Output:

Value of J : 2
Value of F : 5.5

Class to Class Type Conversion:

obj x = obj y;

obj x is an object of class x, obj y is an object of class y.
The class y is converted to class x and the converted value is assigned to obj x. so
conversion takes place from class y to class x.
So y is known as Source Class and x is known as Destination Class.
Conversion can be carried out by either conversion operator in source class and one
argument constructor destination class.

Program to convert once class type to another class type.

class minutes
{
int m;
public:
minutes ()
{
m = 240;
}
get ()
{
return m;
}


void show ()
{
cout<< Minutes = <<m;
}
};
class hours
{
int h;


16
public:
void operator = (minutes x)
void show ()
{
cout<< Hours = <<h;
}
};
void hours :: operator = (minutes x)
{
h = x.get() / 60;
}
int main ()
{
minutes min;
hours hr;
hr = min;
min.show ();
hr.show ();
return 0;
}

Output:

Minutes : 240
Hours : 4















Unit III

1. Explain in detail about the Class Templates and Function Templates.

Class Templates:



17
If the templates associated with classes it is called as class templates. For eg, if the user
creates a class templates for a class Array it would enable the user to create arrays of various
types like int and float.

Syntax:

template class <T>
class name _of_class
{
// class data member and function
}

The statement template class <T> tells the compiler that the following class declaration
can use the template data type. T is the template variable. Both template and class are
keywords. < > is used to declare the template variable that can be used inside the class to
define the template variable.
If the user declares more than one variable then it can be separated by comma.
Template cant be declared inside a class or function. They must be global not
a local.
T k;
Where k is the object for the template variable T
In Non Template function the source code can be increased in size because of
redefining the function separately for each data type.
To avoid the declaration and defining of constructor for different data types the templates
can be used.
In Templates, different values are passed using constructor but for all data types same
template function is used.
Function Templates:

The difference between normal function and member function is that the normal
functions are defined outside the class. They are not members of any class and hence it can be
invoked directly without using dot operator. The member functions are the class members.
They can be invoked using objects of the class which belongs to it.
Syntax:

Template class <T>
Function_name ( )
{ // Code }




18


Progr
am to
define
norm
al
templ
ate
functi
on:

Templ
ate
<class
T>
void
show
(T x)
{

cout
<<
X=
<<x;
}
void
main (
)
{

char c
= A;

int I =
65;
double d = 65.2;
show (c);
show (i);
show (d);
}
Output:

X = A
X = 65
X = 65.2

2. Explain in detail about the Exception Handling Paradigms, Principles and its
Functional Blocks with suitable example.
Program to show values of different
data types using overloaded
constructor.
Class data
{
public:
data (char c)
{ cout<< C= <<c; }
data (int c)
{ cout<< C= <<c; }
};
int main ( )
{
data h (A);
data i (100);
return 0;
}
Output:
C = A
C = 100


Program to show values of different
data types using Constructor and
Templates.
template < class T>
Class data
{
public:
data (T c)
{ cout<< C= <<c; }
};
int main ( )
{
data <char> h (A);
data <int> i (100);
return 0;
}
Output:
C = A
C = 100

data (char c)
data (int c)
data h (A)
data i(100)
data (T c)
data h (A)
data i(100)


19

Developing an error free program is the main objective and intention of the
programmer.
For that the programmer can manually check the errors. The errors are either a
logical or syntax error.
Logical Error is due to the poor understandings of the program and the Syntax Error
is due to the lack of understanding of programming language.
To resolve this C++ have the special feature called Exception Handling which
reduces the errors made by the developer.
An Exception is abnormal termination of the program which is executed at runtime
or it may be called at runtime.
The Exception contains warning messages like invalid argument, insufficient
memory, division by zero and so on.
Principles:

The goal is to create a Routine that detects and sends an exceptional condition in order
to execute suitable action.
The Routine having responsibilities like,
Find the Problem (Hit the Exception),
Inform that an error has occurred (Throw),
Receive the error information (Catch),
Take corrective Actions (Handling the Exception).
An Exception is an object. It is sent from the part of the program where an error occurs
to that part the program which is going to control the error.
There are two types of exceptions,
Synchronous Exceptions,
Asynchronous Exceptions.
Synchronous Exception:
An error such as out of range or overflow belongs to it.
Asynchronous Exception:
Errors that are occurred by the events beyond the control of program such as
keyboard interrupts are belong to this exception.
The Error Handling code consists of two segments, one to detect errors and to throw the
exceptions and other to catch the exceptions and to take appropriate actions.
Mechanism:

C++ provides three mechanisms,

1) The Keyword Try is used at the starting of the exception,
2) The Keyword Throw block is present inside the Try block, Immediately after Try,
Catch block is present.
3) If an exception found then the Throw statement inside the Try block throws an
exception for a Catch block that an error has occurred.


20

Flow Diagram:

Try Block
Find Errors and Throws an Exception
Throw Block
Throws Exception









Program to Throw an Exception:

int main ()
{
int x, y, j;
cout <<Enter the Values of X and Y: ;
cin >> x>>y;
j = x > y ? 0:1;
try
{
if (j ==0)
{ cout << Subtraction (x-y) = << x-y; }
else
{ throw (j); }
}

catch (int k)
{
cout<< Exception Caught : j = << j;
}
return 0;
}

Output:
Enter the Values of X and Y: 7 8
Exception Caught : j = 1
Enter the Values of X and Y: 8 7
Subtraction (x-y) = 1

Catch Block
Gathers Exception from Try Block



21
3. Explain the Exception Specification with example in detail.

This can be used to throw only the specified exception using a throw list
condition.
The Format for this is,
data-type function_name (parameter list) throw (data type list)
{
statements1;
statements2;
}
The data type list indicates the type of exceptions to be thrown.
If the user wants to deny a function from throwing exception then the user can
declare data type list as void.
throw (); // void or vacant list
Program to restrict a function to throw only specified type of exceptions:

void check (int k) throw (int, double)
{
if (k == 1) throw k;
else if (k ==2) throw k;
else if (k ==-2) throw 1.0;
cout<< End of Function Check();
}
void main ()
{
try
{
cout<< k == 1;
check(1);
cout<< k ==2;
check(2);
cout<< k == -2;
check(-2);
}


catch ( char g)
{
cout<< Caught a Char Exception;
}
catch ( int j)
{
cout<< Caught a Integer Exception;
}
catch ( double s)
{ cout<< Caught a Double Exception;}
cout<< End of main;
}



22
Output:

K ==1
Caught a Char Exception
End of main

4. Explain the Uncaught Exception with example in detail.
C++ having two functions to control uncaught exceptions.
a. Terminate () Function
b. Set_terminate () Function
Terminate () Function:

If the exception handler is not defined while the exception is thrown then the
Terminate () function is invoked. Implicitly the abort () function is invoked.
Program to catch uncaught exceptions:

class one { };
class two { };
void main ()
{
try
{
cout << An uncaught exception;
throw two ();
}
catch (one)
{
cout << Exception for one;
}
}






Set_Terminate () Function:

The Set_Terminate () function is used to transfer the control to specified error
handling function. This function requires only one argument which is the function
name. It returns nothing. When no function is specified, the program is terminated by an
implicit call to abort () function.

Program to demonstrate set_terminate () function:

class one { };
class two { };
void skip ()
{ cout << Function skip () is invoked; }


23

void main ()
{
set_terminate (skip);
try
{
cout << Throwing exception;
throw (two);
}
catch (one)
{
cout << Exception for one;
} //At this point function skip is invoked
}

Output:

Throwing exception
Function skip () is invoked

5. Write short notes on Overloading Template Function.

It can be overloaded by normal function or template function. While invoking these
functions an error occurs if no accurate match is met. The compiler follows the following
rules for choosing appropriate function when a program contains overloaded function.

Searches for accurate match of functions; if found invoke that function.
Searches for a template function through which a function that can be invoked with
an accurate match.
Attempts normal overloading declaration for the function.
In case no matches are found, an error will be reported.




Program to overload a Template Function:

Template <class A>
void show (A c)
{
cout <<Template Variable C = << c;
}

void show (int f)
{
cout <<Integer Variable F = << f;
}
int main ( )
{
show (C);


24
show (50);
show (50.25);
return 0;
}

Output:

Template Variable C = C
Integer Variable F = 50
Template Variable C = 50.25























Unit - IV

1. What are the different forms of Inheritance? Explain Multiple Inheritances.
The new classes are created from the existing one is known as Inheritance. The
important property of inheritance is Re usability. The properties of existing class are extended
to new class. New class are called as derived class and the existing class is known as base class

Types (or) Forms of Inheritance:

Single I nheritance:

This contains one base class as well as one derived class.


25







Multiple I nheritances:

This contains two base classes and one derived class.







Multilevel I nheritance:

This contains one base class more than one derived classes.














Hierarchal I nheritance:

This contains one base class more than one derived classes arranged in a level order.










Hybrid or Multi - path Inheritance:

A
B
B
C
A
C
A
B
A
B
C
D


26
This contains one base class more than one derived classes and from the
derived classes another derivation can be done to get sub derived class. This is the
combination of Multiple, Multilevel and Hierarchal Inheritance.















Multiple Inheritances:

This contains two base classes and one derived class.

Program to derive a class from Multiple Base Classes:

Class A {public: int a; }; // Class A declaration
Class B {public: int b; }; // Class B declaration
Class C {public: int c; }; // Class C declaration
Class D {public: int d; }; // Class D declaration
Class E : public A, public B, public C, public D // Class E
{
public:
int e;

void getdata( )
{
cout<<Enter the values of a, b, c, d and e:;
cin >>a>>b>>c>>d>>e;
}
void putdata( )
{
cout<<a=<<a <<b=<<b <<c=<<c<<d=<<d<<e=<<e;
}
};
void main( )
{
E x;
x.getdata( );
x.putdata( );
}

A
B
C
D


27
Output:

Enter the values of a, b, c, d and e: 1 2 3 4 5
a=1 b=2 c=3 d=4 e=5

2. Explain in detail about Virtual Base Class and Abstract Class with example.
Virtual Base Class:

In Multipath Inheritance more than one derived classes try to access the base class
member then the error occurs.

To resolve this ambiguity C++ provides the keyword VIRTUAL.
When the class is declared as virtual then the compiler takes necessary precaution to
avoid the duplication of base class.
After virtual, the base class can be accessed by any number of derived classes.

Before Virtual:

Class A {public: int a; };
Class B : public A
{public: int b; };
Class C : public A
{public: int c; };
Class D : public B, Public C
{public: int d; };

After Virtual:

Class A {public: int a; };
Class B : public Virtual A //Virtual Declaration
{public: int b; };

Class C : Virtual public A Virtual Keyword can be used in either order
{public: int c; };
Class D : public B, Public C
{public: int d; };

Program to declare Virtual Base Classes:

Class A1 {public: int a1; };
Class A2 : public Virtual A1 //Virtual Declaration
{public: int a2; };
Class A3 : Virtual public A1
{public: int a3; };
Class A4 : public A2, Public A3
{
public:
int a4;
void get( )
Ambiguity occurs in accessing the
base class member variable


28
{
cout<<Enter the values of a1, a2, a3 and a4 :;
cin >>a1>>a2>>a3>>a4;
}
void put( )
{
cout<<a1=<<a1 <<a2=<<a2 <<a3=<<a3<<a4=<<a4;
}
};
void main( )
{
A4 a;
a.get( );
a.put( );
}

Output:

Enter the values of a1, a2, a3 and a4: 5 6 7 8
a1=5 a2=6 a3=7 a4=8

Abstract Class:

When a class is not used for creating objects and also if the base class contains the pure
virtual function then it can be called as abstract class.

It can act as a base class only. Its a foundation for the class hierarchy.
It gives a skeleton or structure using which other classes is shaped.
For Example, refer the Virtual Base Class Program. In that the class A1 is not
participating in the program so its an abstract class.




















A
B
C
D
Abstract Class
Virtual
Normal Inheritance


29


In the above program the class A1 acts as a Abstract Class. Though the classes A2 and
A3 are also not contributing for the program it can declare as a Virtual so it can act as a virtual
one. If the keyword isnt present in the declaration then it can also act as an abstract class.

3. Write short notes on Virtual Function and Pure Virtual Functions?
Virtual Function:

The Virtual keyword prevents the compiler from Early Binding.

Virtual Function of a base class can be redefined in the derived class.
The programmer can use a virtual function in a base class and can use the same
function name in any derived class even if the number and type of arguments are
matching.
The matching function overrides the base class function of same name. It can only
be a member function.
Calling of the function without virtual keyword is int b::get(int)
If two functions having same name but different arguments then the C++ compiler
considers them as a different one that is a normal function.

Syntax for declaring a virtual function,

Pointer variable -> function name;

Example:

*point -> get(int);




Rules for Virtual Functions:

It shouldnt be static and must be a member of a class.
Object pointer can access the virtual function. A virtual function may be declared as
Friend for another class.
Constructors cant be declared as a virtual but the destructor can be declared as
virtual.
Virtual functions may have return values.

Program to Use Pointer for Both Base Class and Derived Class and Call the Member
Function Using Virtual Keyword:
Class super
{
public:
virtual void display( )
{
cout<<In Function display() Class Super;
}


30
virtual void show( )
{
cout<<In Function show() Class Super;
}
};
Class sub : public super
{
public:
void display( )
{
cout<<In Function display() Class Sub;
}
void show( )
{
cout<<In Function show() Class Sub;
}
};
int main( )
{
super s;
sub a;
super *point; (instead of using a dot operator to call member Function)
cout<<Pointer points to the Class Super;
point = &s;
point -> display();
point -> show();
cout<<Pointer points to the Class Sub;
point = &a;
point -> display();
point -> show();
return 0;
}

Output:

Pointer points to the Class Super
In Function display() Class Super
In Function show() Class Super
Pointer points to the Class Sub
In Function display() Class Sub
In Function show() Class Sub

Pure Virtual Function:

In many programs the member function of base class is rarely used for doing any
operation. Such functions are called do nothing, dummy function or pure virtual function.

Pure virtual function is always virtual function.
After the declaration of the pure virtual function in a class then the class becomes
abstract class.


31
The derived class without pure virtual functions is called as Concrete Class.
Syntax:

virtual return-type function-name() = 0

Example:

virtual void display( ) = 0;

The zero is used to instruct the compiler that the function is a pure virtual function and
it will not have a definition.

Program for Pure Virtual Function in Base Class:

Class first
{
public:
int b;
first( ) { b = 10; }
virtual void display( ) = 0; // Pure Virtual Function
};
Class second : public first
{
public:
int d;
second( ) { d = 10; }
void display( )
{
cout<<b=<<b<<d=<<d;
}
};
int main( )
{
first *p;
p -> display( ); // Abnormal Program Termination
second s;
p = &s;
p -> display( );
return 0;
}
Because of pure virtual function the base class function display () cant be
invoked by pointer operation. If the user tries to invoke the base class function compiler
throws the Abnormal Program Termination error to the user.

Output:

b = 10
d = 20

4. Explain Dynamic Casting, Down Casting and Cross Casting?


32
Dynamic Casting:

Its a type of RTTI component but doesnt give what type of object a pointer points to
the user instead it safely converts from a pointer to base type to a pointer to a derived
type.
This can be used to convert polymorphic types.

Syntax:

dynamic_cast <Type*> (object or pointer)

This converts pointer to the Type*

Example:

Class base { };
Class derived : public base { };
int main( )
{
base b;
derived d;
base *pb=dynamic_cast <base*> (&d); (Derived to Base)
derived *pd=dynamic_cast <derived*> (&b); (Base to Derived but cant access)
return 0;
}







Down Casting:

The conversion of pointer or reference to the derived class to pointer or reference to
the base class is UP CASTING.
Then the reverse is the DOWN CASTING. This can be achieved by explicitly by
dynamic casting.
Example:

Class base
{
virtual void vf( ) { }
};
Class derived : public base( ) { };
int main( )
{
base b; derived d;
derived *pd = dynamic_cast <derived*> (&b);
return 0;


33
}

Cross Casting:

Another dynamic cast feature is Cross Casting.

Class A { public : virtual ~A( ); };
Class B { public : virtual ~B( ); };
Class C : public A, public B { };
A* ap = new C;
B* bp = dynamic_cast <B*> (ap);

Classes A & B are completely unrelated. By creating an instance to C it can be safely
up cast to A*. Then the pointer to A can be (ap) cross casting to pointer B. In this the A
pointer ap really points at object C. C derives from B.















Unit V

1. Explain Streams in C++ in detail.
The stream is an intermediator or an interface between I/O devices and the user.

The standard C++ library contains the I/O stream functions. A library is nothing but a
set of .obj files.
Stream is a flow of data in bytes in sequence.
If the data is received from i/p devices in sequence then its called as Source or Input
Stream.
If the data is passed to o/p devices in sequence then its called as Destination or Output
Stream.





Input Device
(Keyboard)
Output Device
(Monitor)
Program



Extraction from I / P Stream
Insertion to O / P Stream
I / P Stream
O / P Stream


34







Pre Defined Streams:

Its also called as standard I / O object.
These streams are automatically activated when the program execution starts.
Some of the predefined streams are cin, cout, clog and cerr.
Frequently used unformatted i/p function with cin object
Cin: standard i/p usually keyboards corresponding to stdin in c.

















Frequently used unformatted i/p function with cout object,
Cout: standard o/p usually keyboards corresponding to stdout in c










Clog: It controls errors message that are passed from buffer to the standard error
device. A fully buffered version of Cerr.
Cerr: It controls the unbuffered output data. It catches the error and passes to
standard error device monitor.
Formatting means representation of data with different settings as per the
requirement of the user. The various settings that can be done are number format, field
width etc.
Cin
Getline()
Read ()
Get ()
Cout
Put()
Write()
Flush ()


35
Unformatted means the data accepted or printed with default settings.
Stream Classes:

C++ streams are based on class and object theory.
C++ has number of classes that are used to work with console and file operation. These
classes are called stream classes.





















In this ios is the base class for istream (i/p) and ostream (o/p) which are in turn base
classes for iostream (I/O).
The classes ios can be declared as virtual base class so that, only one copy of its
members are inherited by the iostream.
The class ios has an ability to handle formatted and unformatted data.
The istream gives support for both formatted and unformatted data but the ostream can
handle the formatting data only.

2. Explain Formatted I / O Operations in detail.
C++ provides various formatted console I/O functions for formatting o/p.
The various types are,

ios class function and flags,
Manipulators,
User defined o/p functions

Ios grants operations common to both i/p and o/p. the formatted o/p functions supported by
cout object are,




ios
streambuf istream ostream
iostream
ostream_withassign iostream_withassign istream_withassign
Cout
Width ()
Precision ()
Fill ()
Setf ()


36










Ios Class Functions:

Width () To set the required field width. Output will be displayed in given width.
Precision () To set the number of decimal point for a float value.
Fill () To set a character to fill in the blank space of the field.
Setf () To set various flags for formatting o/p.
Unsetf () To remove flag setting.

Ios::Width( ):
The width () function can be declared in two ways.

Declaration:

a) int width();

If this function is declared as this it returns to the present width setting.


b) int width(int);

If this function is declared, it sets the width as per the given integer and
returns the previous width setting. The setting should be reset for each
I/p or o/p value if width other than the default.

Program to Set Column Width and Display the Character at Specified Position:

void main ( )
{
cout.width (5);
cout<<A;
cout.width (6);
cout<<B;
}

In this the values are always right justified.

Output:



37
A B


Ios::Precision( ):
The precision () function can be declared in two ways.

Declaration:

a) int precision();

It returns the current setting of floating point precision.

b) int precision(int);

If this function is declared, it sets the floating point precision and returns the
previous setting.

Program to Set Precision to two and Display the Float Number:

void main ( )
{
cout.precision (2);
cout<<3.1452;
}

Output:

3.14

Ios::Fill( ):

The fill() function can be declared in two ways.

Declaration:

a) char fill();
It returns the current setting of fill character.
b) char fill(char);

It resets the fill character and returns the previous setting.

Example:

cout.fill(/);
cout.width(5);
cout<<WEL;

Output:


38

/ / W E L

Ios::Setf( ):

The set flag setf() function can be declared in two ways.

Declaration:

a) long setf(long);

It sets the flags according to those marked in the given long.

b) long setf(long sb, long f);

The bits according to that marked in variable f are removed in the data member
x_flags and then reset to those marked in variable sb.

Example:

cout.fill(*);
cout.setf(ios::left, ios::adjustfield);
cout.width(5);
cout<<A;

Output:

A * * * *

3. Explain in detail about I / O Manipulators?
The output formats can be controlled by using manipulators. The file iomanip.h should
be included in the program.

Every ios function has two formats. One for setting and another one is used to know the
previous setting.
But manipulator doesnt return to previous statement. Manipulators can be used with
cout statements as follows,
Cout << m1 << m2 << V;
Where m1 and m2 are manipulators and V is the variable.
The most commonly used manipulators are,

MANIPULATOR DESCRIPTION
EQUIVALENT
TO
Setw(int n) Set the field width to w. Width ( )
Setprecision(int p)
Set floating point
precision to p
Precision ( )


39
Setfill(char f) Set the fill character to f Fill ( )
Setiosflags(long l) Set the format flag to l Setf ( )

Program to display the Formatted Output using Manipulators:

#include <iostream.h>
#include <iomanip.h>
main ( )
{
cout << setw (5) << HA;
cout << setw (10) << setprecision (2) << 2.5556;
cout << setw (4) << setiosflags (ios::left) << HAI;
}

Output:



User Defined Manipulator:

The user can also define own manipulators.







Syntax:

ostream & m_name (ostream & o)
{
statement1;
statement 2;
return o;
}

The m_name is the name of the manipulator.

Example:

ostream & unit (ostream & output)
{
output << inches;
return output;
}

Program to create a User Defined Manipulator:
H A 2 . 5 6 H A I


40

#include <iostream.h>
#include < iomanip.h>
ostream & tab (ostream & O)
{
O<< /t; Code
return O;
}
void main( )
{ Call to Manipulator
cout<<1 << tab << 2 << tab <<3;
}

Output:

1 2 3

4. Write short notes on Filestream Classes in File Handling?
I / O stream of C++ contains a set of classes that define the file handling methods
which include ifstream, ofstream and fstream. These classes are derived from fstream base
and from the corresponding iostream class.





























Manipulator

ios
streambuf
istream ostream
iostream
ofstream fstream ifstream
ofstream


41





Details of File Stream Classes:

CLASSES DESCRIPTION
Filebuf
Its purpose is to set the file buffers to read and write. It
holds constant open prot used in function open ( ) and close
( ) as a member.
Fstreambase
Serve as a base for fstream, ifstream and ofstream class
which contains open ( ) and close ( ) function.
Ifstream
Provides i/p operation contains open ( ) with default i/p
mode. Inherits the function get ( ), read ( ) from istream.
Ofstream
Provides o/p operation contains open ( ) with default i/p
mode. Inherits the function put ( ), write ( ) from ostream.
Fstream
Contains open ( ) with default i/p mode. Inherits all
function from istream and ostream classes through
iostream.





5. Explain ANSI String Objects and Namespaces in detail.

ANSI String Object:

A String is nothing but a sequence of characters. String contains small and capital letters,
numbers and symbols. It is an array of character type. Each element of string occupies a byte in
a memory. The last character of string is null (\0) character.

String class can be used for the manipulation of the string in C++. String class may
contain constructors, member functions and operators. By these string class the user can,

Create String Object
Reading and Displaying the String Object
Modifying, Adding, Comparing and Accessing the String Object.

String Constructor:



42
String ( ) Produces an empty string
String (const char*text)
Produces a string object from a null
ended string
String (const string&text)
Produces a string object from other
string object

The declaration and initialization of string object is,

String text; // Using Constructor without Argument

String text (C++); // Using Constructor with One Argument

Text1 = text2; // Assignment of Two Strings











The Operators used in string manipulators are,

OPERATOR WORKING
= Assignment
+ Joining two or more strings
+= Concatenation And Assignment
==, !=, <, <=, >, >=
Equal To, Not Equal To, Lesser
Than, Less Than Or Equal,
Greater Than, Greater Than Or
Equal
[ ] Subscript
<< Insertion
>> extraction


43


Program to declare string object to perform assignment and concatenation operations:

#include <string> // String Container
int main ( )
{
string text;
string text1 (C++); // Constructor without argument
string text2 (OOP); // Constructor with argument
cout << Text1:<< text1<<\n;
cout << Text2:<< text2<<\n;
text = text1; // Assignment
cout << Text:<<text;
text = text1 + +text2;
cout << Now text: << text;
return 0;
}

Output:

Text1 = C++
Text2 = OOP
Text = C++
Now text = C++ OOP




String Manipulation Functions:

The various string manipulation functions are,

Append ( ) Adds one string at the end of another string
Assign ( ) Assigns a specified part of the string
Begin ( ) Returns a reference to the beginning of a string
Compare ( ) Compare the two strings
Empty ( ) Returns false if the string isnt empty, or else true
End ( ) Returns a reference to the termination of the string

Program to insert one string at end of another string using append ( ):

int main ( )
{
string s1 (abc);
string s2 (hij);
cout << s1= <<s1;
cout << After Append;
s1.append (s2);
cout << s1= <<s1;


44
return 0;
}

Output:

s1 = abc
After Append
s1 = abchij

Namespaces:

C++ allows variables with different scopes such as global, local with different blocks
and classes. This can be done by using keyword namespace which was introduced by ANSI
C++. The C++ Standard Library is the best example for namespace. The statement Namespace
Std tells the compiler that the members of this namespace are to be used in the current
program.

Declaration:

Declaration of namespace is as same as class declaration except that the namespaces are
not terminated with semicolon.

Namespace namespace_identifier
{
// Definitions of variables, functions and class
}


Example:

Namespace num
{
int n;
void show (int k) {cout << k;}
}

If the user wants to assign a value for variable n then the scope resolution operator can
be used.

Example:

Num :: n = 50;

Accessing Namespaces:

1. Using namespace namespace_identifier // Directive Statement
It allows the access to the elements without scope resolution operator.

2. Using namespace_identifier :: member // Declaration Statement


45
It allows access to only the given elements
Examples:

1. Using namespace num
N = 10;
Show (15);
2. Using namespace :: n
M = 20;
Show (14);

Nested Namespaces:

When one namespace is nested in another namespace it is known as nested namespace.

Example:

Namespace num
{
statement 1;
Namespace num1
{
int k = 0;
}
Statement 2;
}
The variable k can be accessed as cout << num :: nium1 :: k.
Anonymous or Unnamed Namespace:

A namespace without name is known as anonymous namespace. The members of
anonymous namespaces can access globally in all scopes. Frequent use of such namespaces is
to protect the global data from same name class among files. Each file possesses separate
anonymous namespace.

Program to declare nested and anonymous namespace:

Namespace num
{
int j = 200;
Namespace num1
{
int k = 400;
}
}
Namespace // Unnamed Namespace
{
int j = 500;
}
void main ( )
{


46
cout << J= << num :: j;
cout << K= << num :: num1 :: j;
cout << J= << j;
}

Output:

J = 200
K = 400
J = 500

Standard Namespace Std:

This statement inserts the complete library in the current program. This is same as
including a header file. The user can access all class, functions and templates declared inside
this namespace. Mostly here the directive method can be used to access all members of
namespace directly.

Guidelines for Defining Namespaces:

Namespaces arent terminated by semicolon like class.
Declarations done outside the namespaces are considered as member of global
namespace.
Members of namespaces are defined inside the scope of the namespace.

You might also like