doc cs2203oop2marks (1)

33
CS 2203 OBJECT-ORIENTED PROGRAMMING 3 0 0 3 (Common to CSE & IT) Aim: To understand the concepts of object-oriented programming and master OOP using C++. UNIT I 9 Object oriented programming concepts – objects – classes – methods and messages – abstraction and encapsulation – inheritance – abstract classes – polymorphism. Introduction to C++ – classes – access specifiers – function and data members – default arguments – function overloading – friend functions – const and volatile functions - static members – Objects –  pointers and objects – constant objects – nested classes – local classes UNIT II 9 Con str uc tor s – def aul t con str uct or – Par ame ter ize d construc tor s – Constr uc tor wit h dyn amic allocation – copy constructor – destructors – operator overloading – overloading through friend functions – overloading the assignment operator – type conversion – explicit constructor UNIT III 9 Fun cti on and cla ss templa tes - Excep tion han dli ng try -ca tch -th row par adi gm exc ept ion specification – terminate and unexpected functions – Uncaught exception. UNIT IV 9 Inheritance – public, private, and protected derivations – multiple inheritance - virtual base class – abstract class – composite objects Runtime polymorphism – virtual functions – pure virtual functions  – RTTI – typeid – dynamic casting – RTTI and templates – cross casting – down casting . UNIT V 9 Streams and formatted I/O – I/O manipulators - file handling – random access – object serialization – namespaces - std namespace – ANSI String Objects – standard template li brary.  Total: 45 TEXT BOOKS: 1. B. Trivedi, “Programming with ANSI C++”, Oxford Univers ity Press, 2007. REFERENCES: 1. Ira Pohl, “Object Orien ted Prog rammin g using C++”, Pear son Edu cation, Second Edition Reprint 2004.. 2. S. B. Lipp man, Jos ee Lajo ie, Barb ara E. Moo , “C++ Pri mer”, Fo urth Editio n, Pears on Education, 2005. 3. B. Strous trup, “Th e C++ Programming lan guage ”, Third edi tion , Pearson Ed ucati on, 2004 .

Upload: vikneshwar-vicky

Post on 07-Apr-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 1/33

CS 2203 OBJECT-ORIENTED PROGRAMMING 3 0 0 3

(Common to CSE & IT)

Aim: To understand the concepts of object-oriented programming and master OOP using C++.

UNIT I

9

Object oriented programming concepts – objects – classes – methods and messages – abstraction and

encapsulation – inheritance – abstract classes – polymorphism.Introduction to C++ – classes – access specifiers – function and data members – default arguments – 

function overloading – friend functions – const and volatile functions - static members – Objects – 

 pointers and objects – constant objects – nested classes – local classes

UNIT II

9

Constructors – default constructor – Parameterized constructors – Constructor with dynamic

allocation – copy constructor – destructors – operator overloading – overloading through friend

functions – overloading the assignment operator – type conversion – explicit constructor 

UNIT III 9

Function and class templates - Exception handling – try-catch-throw paradigm – exceptionspecification – terminate and unexpected functions – Uncaught exception.

UNIT IV 9

Inheritance – public, private, and protected derivations – multiple inheritance - virtual base class – 

abstract class – composite objects Runtime polymorphism – virtual functions – pure virtual functions

 – RTTI – typeid – dynamic casting – RTTI and templates – cross casting – down casting .

UNIT V 9

Streams and formatted I/O – I/O manipulators - file handling – random access – object serialization – 

namespaces - std namespace – ANSI String Objects – standard template library.

  Total: 45

TEXT BOOKS:

1. B. Trivedi, “Programming with ANSI C++”, Oxford University Press, 2007.

REFERENCES:

1. Ira Pohl, “Object Oriented Programming using C++”, Pearson Education, Second EditionReprint 2004..

2. S. B. Lippman, Josee Lajoie, Barbara E. Moo, “C++ Primer”, Fourth Edition, Pearson

Education, 2005.

3. B. Stroustrup, “The C++ Programming language”, Third edition, Pearson Education, 2004.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 2/33

UNIT I

9

Object oriented programming concepts – objects – classes – methods and messages – abstraction and

encapsulation – inheritance – abstract classes – polymorphism.

Introduction to C++ – classes – access specifiers – function and data members – default arguments – function overloading – friend functions – const and volatile functions - static members – Objects – 

 pointers and objects – constant objects – nested classes – local classes

2 Marks

1) Give the evolution diagram of OOPS concept.

Machine language

Procedure language

Assembly language

OOPS

2) What is Procedure oriented language?

Conventional programming, using high-level language such as COBOL, FORTRAN and C arecommonly known as Procedure oriented language (POP). In POP number of functions are written to

accomplish the tasks such as reading, calculating and printing.

3) Give some characteristics of procedure-oriented language.

• Emphasis is on doing things (algorithms).

• Larger programs are divided into smaller programs known as functions.

• Most of the functions share global data.

• Data move openly around the system from function to function.

• Employs top-down approach in program design.

Function-1 Function-2 Function-3

Function-4 Function-5

Function-6 Function-7 Function-8Main program

4) Write any four features of OOPS.

• Emphasis is on data rather than on procedure.

• Programs are divided into objects.

• Data is hidden and cannot be accessed by external functions.

• Follows bottom -up approach in program design.

5) What are the basic concepts of OOS?

• Objects.

• Classes.

• Data abstraction and Encapsulation.• Inheritance.

• Polymorphism.

• Dynamic binding.• Message passing.

6) What are objects?

Objects are basic run-time entities in an object-oriented system. They may represent a person, a place,

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 3/33

a bank account, a table of data or any item that the program has to handle. Each object has the data

and code to manipulate the data and theses objects interact with each other.

7)What is a class?

• The entire set of data and code of an object can be made a user-defined data type with the help of a

class.

• Once a class has been defined, we can create any number of objects belonging to the classes.

• Classes are user-defined data types and behave like built-in types of the programming language.

8) what is encapsulation?

Wrapping up of data and function within the structure is called as encapsulation.

9)What is data abstraction?

The insulation of data from direct access by the program is called as data hiding or information

 binding.

The data is not accessible to the outside world and only those functions, which are wrapped in the

class, can access it.

10)What are data members and member functions?

Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,weight, and cost and uses functions to operate on these attributes.

The attributes are sometimes called as data members because they hold information. The functions

that operate on these data are called as methods or member functions.

Eg: int a,b; // a,b are data members

Void getdata ( ) ; // member function

11)What is dynamic binding or late binding?

Binding refers to the linking of a procedure to the code to be executed in response to the call.

Dynamic binding means that the code associated with a given procedure call is not known until thetime of the call at the run-time.

12)Write the process of programming in an object-oriented language?• Create classes that define objects and their behavior.

• Creating objects from class definition.

• Establishing communication among objects.

13)Give any four advantages of OOPS.

• The principle of data hiding helps the programmer to build secure programs that cannot be invaded

 by code in other parts of the program.

• It is possible to have multiple instances of an object to co-exist without any interference.

• Object oriented programming can be easily upgraded from small to large systems.

• Software complexity can be easily managed.

14)What are the features required for object-based programming Language?• Data encapsulation.

• Data hiding and access mechanisms.

• Automatic initialization and clear up of objects.• Operator overloading.

15)What are the features required for object oriented language?

• Data encapsulation.

• Data hiding and access mechanisms.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 4/33

• Automatic initialization and clear up of objects.

• Operator overloading.

• Inheritance.

• Dynamic binding.

16)Give any four applications of OOPS

• Real-time systems.

• Simulation and modeling.

• Object-oriented databases.

• AI and expert systems.

17) Give any four applications of c++?

• Since c++ allows us to create hierarchy-related objects, we can build special object-orientedlibraries, which can be used later by many programmers.

• C++ are easily maintainable and expandable.

• C part of C++ gives the language the ability to get close to the machine-level details.

• It is expected that C++ will replace C as a general-purpose language in the near future.

18) What are tokens?

The smallest individual units in a program are known as tokens. C++ has the following tokens,

• Keyword

• Identifiers• Constants

• Strings

• Operator 

19)What are keywords?

The keywords implement specific C++ language features. They are explicitly reserved identifiers and

cannot be used as names fro the program variables or other user defined program elements.

Eg: go to, If, struct , else ,union etc.

20) Rules for naming the identifiers in C++.

• Only alphabetic characters, digits and underscore are permitted.

• The name cannot start with a digit.• The upper case and lower case letters are distinct.• A declared keyword cannot be used as a variable name.

21)What are the operators available in C++?

All operators in C are also used in C++. In addition to insertion operator << and extraction operator 

>> the other new operators in C++ are,

: Scope resolution operator 

: : * Pointer-to-member declarator 

->* Pointer-to-member operator 

.* Pointer-to-member operator 

delete Memory release operator 

endl Line feed operator new Memory allocation operator 

setw Field width operator 

22)What is a scope resolution operator? 

Scope resolution operator is used to uncover the hidden variables. It also allows access to global

version of variables.

Eg:#include<iostream. h>

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 5/33

int m=10; // global variable m

void main ( )

{

int m=20; // local variable m

cout<<”m=”<<m<<”\n”;cout<<”: : m=”<<: : m<<”\n”;

}

output:

2010 (: : m access global m)

Scope resolution operator is used to define the function outside the class.

Syntax:

Return type <class name> : : <function name>

Eg:

Void x : : getdata()

23) What are free store operators (or) Memory management operators? 

 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;

24) What are manipulators?

Setw, endl are known as manipulators.

Manipulators are operators that are used to format the display. The endl manipulator when used in an

output statement causes a linefeed to be inserted and its effect is similar to that of the newline

character”\n”.

Eg:Cout<<setw(5)<<sum<<endl;

25) What do you mean by enumerated datatype? An enumerated datatype is another user-defined datatype, which provides a way for attaching names

to numbers, thereby increasing comprehensibility of the code.The syntax of an enum statement is

similar to that of the struct statesmen.

Eg:

enum shape{ circle, square, triangle}

enum color{ red, blue, green, yellow}

26) What are symbolic constants? 

There are two ways for creating symbolic constants in C++:

• Using the qualifier constant.

• Defining a set of integer constants using enum keyword.The program in any way cannot modify the value declared as constant in c++.

Eg:

Const int size =10;

Char name [size];

27)What do you mean by dynamic initialization of variables?

C++ permits initialization of the variables at run-time. This is referred to as dynamic initialization of 

variables.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 6/33

In C++ ,a variable can be initialized at run-time using expressions at the place of declaration as,

……..

…......

int n =strlen(string);

……..float area=3.14*rad*rad;

Thus declaration and initialization is done simultaneously at the place where the variable is used for 

the first time.

28) 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 interchancheably to represent that variable.

Syntax :

Data-type &reference-name = variable-name

Eg:

float total = 100;

float sum = total;

29)What is member-dereferencing operator?

C++ permits to access the class members through pointers. It provides three pointer-to-member operators for this purpose,

: :* To declare a pointer to a member of a class.* To access a member using object name and a pointer to the member 

->* To access a member using a pointer to the object and a pointer to that member.

30)what is function prototype ?

The function prototype describes function interface to the compiler by giving details such as

number ,type of arguments and type of return values

Function prototype is a declaration statement in the calling program and is of the

following

Type function_name(argument list); Eg float volume(int x,float y);

31)what is an inline function ?

An inline function is a function that is expanded in line when it is invoked. That is compiler replaces

the function call with the corresponding function code.

The inline functions are defined as Inline function-header 

{

function body

}

32) Write some situations where inline expansion may not work  

• for functions returning values, if loop, a switch, or a goto exists

• for functions not returning values ,if a return statement exists

• if function contain static variables• if inline functions are recursive

33)what is a default argument ?

Default arguments assign a default value to the parameter, which does not have matching argument in

the function call. Default values are specified when the f unction is declared.

Eg : float amount(float principle,int period,float rate=0. 15)

Function call is

Value=amount(5000,7);

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 7/33

Here it takes principle=5000& period=7

And default value for rate=0.15

Value=amount(5000,7,0.34)

Passes an explicit value 0f 0.34 to rate

We must add default value from right to left

34) What are constant arguments ? 

keyword is const. The qualifier const tells the compiler that the function should not modify the

argument. The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers

eg: int strlen( const char *p);

35) How the class is specified ?

Generally class specification has two parts

• class declaration

It describes the type and scope of its member 

• class function definition

It describes how the class functions are implemented

The general form is

Class class_name

{ private:

variable declarations;function declaration;

 public:

variable declaration;

function declaration;

};

36) How to create an object ?

Once the class has been declared, we can create variables of that type by using the classname

Eg:classname x; //memory for x is created

37) How to access a class member ? 

object-name. function-name(actual arguments)

eg:x.getdata(100,75.5);

38) How the member functions are defined ?

Member functions can be defined in two ways

• outside the class definition

Member function can be defined by using scope resolution operator::General format is

Return type class_ name::function-name(argument declaration)

{

}• Inside the class definition

This method of defining member function is to replace the function declaration by the actual function

definition inside the class. It is treated as inline function

Eg:class item

{

int a,b ;

void getdata(int x,int y)

{

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 8/33

a=x;

 b=y;

};

39) What is static data member?

Static variable are normally used to maintain values common to the entire class.Feature:

• It is initialized to zero when the first object 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

• It is only visible within the class, but its life time is the entire class type and scope of each staticmember variable must be defined outside the class

• It is stored separately rather than objects

Eg: static int count//count is initialized to zero when an object is created.

int classname::count;//definition of static data member 

40) What is static member function? 

A member function that is declared as static has the following properties

• A static function can have access to only other static member declared in the same class

• A static member function can be called using the classname as follows

classname ::function_name;

41) How the objects are used as function argument?This can be done in two ways

• A copy of the entire object is passed to the argument• Only address of the objects is transferred to the f unction

42) What is called pass by reference?

In this method address of an object is passed, the called function works directly on the actual

arguments.

 

43) Define const member

If a member function does not alter any data in the class, then we may declare it as const member 

function as

Void mul(int ,int)const;

44) Define pointers to member 

It is possible to take the address of a member of a class and assign it to a pointer. The address of a

member can be obtained by applying the operator &to a “fully qualified” class member name. A class

member pointer can be declared using the operator::*with the class name.

Eg: class A

{

int m; public:

void show( );

};

 pointer to member m is defined asint A::*ip=&A::m;

A::*->pointer to member of A class

&A::m->address of the m member of A class

45) When the deferencing operator ->* is used? 

It is used to access a member when we use pointer to both the object and the member.

47) When the deferencing operator .* is used?

It is used to access a member when the object itself is used as pointers.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 9/33

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 10/33

}

class student

{

………

};student s1(a);}

PART-B

1) Describe the advantages of OOP(8)2) What are the differences between pointers to constants and constant

 pointers?(8)

3) Describe the applications of OOP technology.

4) Explain object-oriented paradigm with al1its essential elements

5) State the merits and demerits of object oriented methodology

6) Explain the following concepts of object oriented programming in detail

with an example.

(i) Data abstraction

(ii) Inheritance

(iii) Polymorphism

(iv) Objects

7)Write short notes on access specifiers8)Explain default arguments with example

9)Explain about friend function with suitable example10)What is a static member and what are common characteristics

11)Explain about pointers with example

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 11/33

UNIT II

9

Constructors – default constructor – Parameterized constructors – Constructor with dynamic

allocation – copy constructor – destructors – operator overloading – overloading through friend

functions – overloading the assignment operator – type conversion – explicit constructor 

1) Define constructor

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

Eg:

integer Class

{

……

 public:

integer( );//constructo r ………

}

2) Define default constructor

The constructor with no arguments is called default constructor 

Eg:

Class integer 

{

int m,n;

Public:

Integer( );

…….};

integer::integer( )//default constructor 

{

m=0;n=0;

}

the statement

integer a;

invokes the default constructor 

3) Define parameterized constructor 

constructor with arguments is called parameterized constructor 

Eg;Class integer 

{ int m,n;

 public:

integer(int x,int y)

{ m=x;n=y;

}

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

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 12/33

1.By calling the constructor explicitly

eg: integer int1=integer(10,10);

2.By calling the constructor implicitly

eg: Integer int1(10,10);

4) Define default argument constructor 

The constructor with default arguments are called default argument constructor 

Eg:

Complex(float real,float imag=0);The default value of the argument imag is 0

The statement complex a(6.0)

assign real=6.0 and imag=0

the statement

complex a(2.3,9.0)

assign real=2.3 and imag=9.0

5) What is the ambiguity between default constructor and default argument

constructor ?

The default argument constructor can be called with either one argument or no arguments. when

called with no arguments ,it becomes a default constructor. When both these forms are used in a

class ,it cause ambiguity for a statement such as A a;The ambiguity is whether to call A::A() or A::A(int i=0)

6) Define copy constructor

A copy constructor is used to declare and initialize an object from another object. It takes a reference

to an object of the same class as an argument

Eg: integer i2(i1);

would define the object i2 at the same time initialize it to the values of i1.

Another form of this statement is

Eg: integer i2=i1;The process of initializing through a copy constructor is known as copy initialization .

7) Define dynamic constructorAllocation of memory to objects at time of their construction is known as dynamic constructor. The

memory is allocated with the help of the NEW operator 

Eg:

Class string

{

char *name;

int length;

 public:string( )

{

length=0;

name=new char[ length +1];}

void main( )

{

string name1(“Louis”),name3(Lagrange);

}

8) Define const object

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 13/33

We can create constant object by using const keyword before object declaration.

Eg: Const matrix x(m,n);

9) Define destructor

It is used to destroy the objects that have been created by constructor. Destructor name is same as

class name preceded by tilde symbol(~)

Eg;~integer()

{

}

A destructor never takes any arguments nor it does it return any value. The compiler upon exit from

the program will invoke it. new Whenever operator is used to allocate memory in the constructor, we

should

use delete to free that memory.

10) Define multiple constructors (constructor overloading).

The class that has different types of constructor is called multiple constructors

Eg:

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

class integer 

{

int m,n;

 public:

integer( ) //default constructor 

{

m=0;n=0;

}integer(int a,int b) //parameterized constructor 

{

m=a; n=b;}

integer(&i) //copy constructor 

{

m=i. m;

n=i.n;

}

void main()

{

integer i1; //invokes default constructor 

integer i2(45,67);//invokes parameterized constructor 

integer i3(i2); //invokes copy constructor 

}

11) Write some special characteristics of constructor 

• T hey 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

• They can have default arguments

• Constructors cannot be virtual f unction

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 14/33

12) How the objects are initialized dynamically?

To call parameterized constructor we should the pass values to the object ie,for the constructor 

integer(int a,int b) it is invoked by integer a(10,18)

this value can be get during run time. i.e., f or above constructor int p,q;

cin>>p>>q;

integer a(p,q);

13)Define Inline Function?

Inline function is defined as a function definition such that each call to the function is in effect,

replaced by the statements that define the function. It is expanded in line when it is invoked. The

general form is

inline function-header 

{

function body

}

14)Explain return by reference with an example.

A function can also return a reference. Consider the following function

int & max( int &x , int &y){ if(x>y)

return x;else

return y;

}

Since the return type of max ( ) is int & the function returns reference to x or y (and not the values).

Then a function call such as max ( a , b) will yield a reference to either a or b depending on their 

values.

The statement

max ( a , b) = -1;

is legal and assigns –1 to a if it is larger, otherwise –1 to b.

15) What is operator overloading?

C++ has the ability to provide the operators with a special meaning for a data type. This mechanism

of giving such special meanings to an operator is known as Operator overloading. It provides a

flexible option for the creation of new definitions for C++ operators.

16) List out the operators that cannot be overloaded. 

• Class member access operator (. , .*)

• Scope resolution operator (::)• Size operator ( sizeof )

• Conditional operator (?:)

17) What is the purpose of using operator function? Write its syntax.To define an additional task to an operator, we must specify what it means in relation to the class to

which the operator is applied. This is done by Operator function , which describes the task. Operator 

functions are either member functions or friend functions. The general form is

return type classname :: operator (op-arglist )

{

function body

}

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

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 15/33

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

the function name.

18) Write at least four rules for Operator overloading.

• Only the existing operators can be overloaded.

• The overloaded operator must have at least one operand that is of user defined data type.

• The basic meaning of the operator should not be changed.

• Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.

19) How will you overload Unary & Binary operator using member functions?

When unary operators are overloaded using member functions it takes no explicit arguments andreturn no explicit values. When binary operators are overloaded using member functions, it takes one

explicit argument. Also the left hand side operand must be an object of the relevant class.

20) How will you overload Unary and Binary operator using Friend functions?

When unary operators are overloaded using friend function, it takes one reference argument (object of 

the relevant class) When binary operators are overloaded using friend function, it takes two explicit

arguments.

21) How an overloaded operator can be invoked using member functions? In case of Unary operators, overloaded operator can be invoked as op object_name or object_name op

In case of binary operators, it would be invoked as Object . operator op(y)

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

22) How an overloaded operator can be invoked using Friend functions?

In case of unary operators, overloaded operator can be invoked as Operator op (x);

In case of binary operators, overloaded operator can be invoked as Operator op (x , y)

23) List out the operators that cannot be overloaded using Friend function.

• Assignment operator =

• Function call operator ( )• Subscripting operator [ ]• Class member access operator 

24) Explain basic to class type conversion with an example.

Conversion from basic data type to class type can be done in destination class.

Using constructors does it. Constructor takes a single argument whose type is to be converted.

Eg: Converting int type to class type

class time{

int hrs,mins;

 public:

………….Time ( int t) //constructor 

{

hours= t/60 ; //t in minutes

mins =t % 60;

}

};

Constructor will be called automatically while creating objects so that this conversion is done

automatically.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 16/33

25) Explain class to basic type conversion with an example.

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

in the source class itself.

Eg: vector : : operator double( ){

double sum=0;

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

sum=sum+v[ i ] *u[ i ] ;return sqrt ( sum ) ;

}

This function converts a vector to the corresponding scalar magnitude.

26) Explain one class to another class conversion with an example.

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

conversion. Here constructor is used in destination class and casting operator function is used in

source class.

Eg: objX = objY

objX is the object of class X and objY is an object of class Y. The class Y type data is converted into

class X type data and the converted value is assigned to the obj X. Here class Y is the source class

and class X is the destination class.

PART-B

1)Explain copy constructor with suitable C++ coding.

2)List out the rules for overloading operators

3)State the rules to be followed while overloading an operator. Write a program to illustrate an

overloading

4)What is operator overloading? How many arguments are required in the definition of an overloaded

 binary operator 

5)What is constructor? Explain the types of constructor with an suitable exampleWrite a program to

overload = operator. Assign values of data members of one object to another object of the same type.6)Explain default constructors with suitable example

7)Explain constructor with Dynamic Allocation give example

8)Write short notes on:

i)Type conversions

ii)Explicit constructor 

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 17/33

UNIT III 9

Function and class templates - Exception handling – try-catch-throw paradigm – exception

specification – terminate and unexpected functions – Uncaught exception.

1) What are Exceptions?Exceptions which occur during the program execution, due to some fault in the input data

2) What are the two types of exceptions?

Exceptions are classifieds into

a)Synchronous exception

 b) Asynchronous exception

3) What is a synchronous exception?

The technique that is not suitable to handle the current class of data, within the program are

known as synchronous exception

4) What is an Asynchronous exception?The exceptions caused by events or faults unrelated to the program and beyond the control of 

 program are called asynchronous exceptions

5) What are the blocks used in the Exception Handling?

The exception-handling mechanism uses three blocks

1)try block 

2)throw block 

3)catch block 

The try-block must be followed immediately by a handler,which is a catch-block.

If an exception is thrown in the try-block 

6) Draw the Exception handling model?

Invoke function having throw block 

exception

exception

Try block 

Perform operation which may

throw or invoke external function

if needed

Throw block 

If(failure)

Throw object;

Catch block 

Catches all exceptions thrown from

within try block or by function

invoked within a try block 

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 18/33

7) Write the syntax of try construct

The try keyword defines a boundary within which an exception can occur.A block of code in

which an exception can occur must be prefixed by the keyword try.Following the try keyword is a

 block of code enclosed by braces.This indicates that the program is prepared to test for the existence

of exceptions

Keyword

try

{

//code raising exception or referring to a function raising exception

}

catch(type_id1)

{

//actions for handling an exception

}…

…catch(type_idn)

{

//actions for handling an exception

}

8) Write the syntax of catch construct

The exception handler is indicated by the catch keyword.It must be used immediately after 

the statements marked by the try keyword.The catch handler can also occur immediately after another 

catch.Each handler will only evaluate an exception that matches,or can be covered to the type

specified in its argument list.

Keyword object name or nameless object

Catch(T)

{

// actions for handling an exception}

9) Write the syntax of throw constructThe keyword throw is used to raise an exception when an error is generated in the

computation.The throw expression initializes a temporary object of the type T(to match the type of 

argyment arg)used in throw(T arg)

 Named object, nameless object

Keyword

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 19/33

throw T;

10) List out the tasks to be performed for error handling code

1)Detect the problem causing exception(Hit the exception)

2)Inform that an error has occurred(Throw the exception)

3)Receive the error information(Catch the exception)4)Take corrective actions(Handle the exceptions)

11) Write the steps to be performed when an exception is raised

1)The program searches for a matching handler 

2)If a handler is found, the stack is unwound to that point

3)Program control is transferred to the handler 

4)If no handler is found, the program will invoke the terminate()function. If no exceptions are

thrown, the program executes in the normal fashion

12) Write the syntax of specifying a list of exceptions

Function definition List of exceptions that can be raised

FunctionSpecification throw(type id1,type id2,……)

{

//Function body raising exceptions if error occurs

}

13) Write the syntax of catch all construct

Three dots:indicate catch all exceptions

Catch(…)

{

//actions for handling an exception

}

14) What is a secure operation?

All destructors in a C++ program should have an empty specification throw().This is called

secure operations

15) What is stack unwinding?

The process of calling destructor for automatic objects constructed on the path from a try-

 block to a thrown expression is called stack unwinding

16) Write the functions to handle uncaught exceptions

1)terminate()

2)set_terminate()

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 20/33

3)unexpected()

4)set_unexpected()

17) What are the types of fault tolerant design techniques

Fault tolerant software design techniques can be classified into the following

1)N-version programming

2)Recovery block 

18) List out some of the error handling functions

a)eof()-Returns true if end-of-file is encountered

 b)fail()-Returns true when an input or output operation has failed

c)bad()-Returns true if invalid operation is attempted by or any uncoverable error has

occurred

d)good()-Returns true if no error has occurred

19) What are the two types of errors or bugs?

a)Logical errors-errors occur due to poor understanding of the problem and solution

 procedure b)Syntatic errors-errors that arise due to poor understanding of the language itself.

20) What is function template?

A function template specifies how an individual function can be constructed. The

limitation of such functions is that they operate only on a particular data type. It can be overcome by

defining that function as a function template or generic function.

21)Write the syntax of function template

template<class T,…>

ReturnType FuncName(arguments)

{…..//body of the function template

…..

}

22)What is class template?

Classes can also be declared to operate on different data types. Such classes are called class

templates. A class template specifies how individual classes can be constructed similar to normal

class specification

23)Write the syntax of class template

template <class T1,class T2,…>class classname

{

T1 data1;

….

//functions of template arguments T1,T2,….

void func1(T1 a,T2 &b);

T func2(T2 *x,T2 *y);

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 21/33

};

PART-B

1) Discuss the need for exception with try, catch and throw keywords

2) What is Function Template? Write the syntax for function template. Write an example program for 

function template.3) What is class template? Write the syntax for class template. Write an example program for class

template.

4) What are Exceptions? What are the two types of exceptions? Draw the Exception handling model?

5) What are uncaught exceptions? Write the functions to handle uncaught exceptions with a suitable

example

6) What are Exceptions? What are the two types of exceptions? Write the syntax of try construct.

Write the syntax of catch construct. Write the syntax of throw construct with an example

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 22/33

UNIT IV 9

Inheritance – public, private, and protected derivations – multiple inheritance - virtual base class – 

abstract class – composite objects Runtime polymorphism – virtual functions – pure virtual functions

 – RTTI – typeid – dynamic casting – RTTI and templates – cross casting – down casting .

1) What is meant by inheritance? 

Inheritance is the process by which objects of one class acquire the properties of another class. It

supports the concept of hierarchical classification. It provides the idea of reusability. We can add

additional features to an existing class without modifying it by deriving a new class from it.

2)List the rules for inheritance

1)The default mode is private2)Difficult to inherit the base class private members

3)The base class public and protected member functions are considered as public and

 protected member functions in derived class,When those class is publicly inherited from base class

4)The base class public and protected member functions are considered as private member 

function in derived class,when those class is privately inherited from base class

3)List the class member’s visibility

There are three visibilities of class members.They are

i) Public visibility

ii)Private visibility

iii)Protected visibility

4)Explain the public visibility

The class members are visible to the base class,derived classes and outside the class throughthe objects

5)Explain the private visibilityThe class members are visible only to the base class itself but not to the derived class

6)Explain the protected visibility

The class members are visible to the base and derived classes

7) What is meant by single inheritance?

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

Eg:

Base class

Derived class

Here class A is the base class from which the class D is derived. Class D is the public

derivation of class B hence it inherits all the public members of B. But D cannot access private members of B.

8) What is multiple inheritance? 

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

Eg: Base classes

Derived class

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

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 23/33

9) What is hierarchical inheritance? 

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

hierarchical inheritance.

Eg : Hierarchical classification of students in University

A

B

A

CB

10) What is multilevel inheritance?

If a class is derived from a class, which in turn is derived from another class, is called multilevel

inheritance. This process can be extended to any number of levels.

Eg:

Base class Grand father Intermediate

Base class Father 

Derived class Child

11) What is hybrid inheritance? It is the combination of one or more types of inheritance.

Multilevel

inheritance

Multiple

inheritance

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

Student

Arts Engineering M e d i c a l

CSE ECE CivilA

B

CStudentTest

Result

Sports

12) What is meant by Abstract base class?

A class that serves only as a base class from which derived classes are derived. No objects of an

abstract base class are created. A base class that contains pure virtual function is an abstract baseclass.

13) Write short notes on virtual base class.

A base class that is qualified as virtual in the inheritance definition. In case of multiple inheritance, if the base class is not virtual the derived class will inherit more than one copy of members of the base

class. For a virtual base class only one copy of members will be inherited regardless of number of 

inheritance paths between base class and derived class.

Eg: Processing of students’ results. Assume that class sports derive the roll

number from class student. Class test is derived from class Student. Class result is

derived from class Test and sports. As a virtual base class

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 24/33

14)What are virtual functions?

A function qualified by the ‘virtual’ keyword is called virtual function. When a virtual function is

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

used.

15)Write some of the basic rules for virtual functions 

• Virtual f unctions must be member of some class.

• They cannot be static members and they are accessed by using object pointers

• Virtual f unction in a base class must be defined.• Prototypes of base class version of a virtual function and all the derived class versions must be

identical.

• If a virtual function is defined in the base class, it need not be redefined in the derived class.

16) What are pure virtual functions? Write the syntax.

A pure virtual function is a function declared in a base class that has no definition relative to the base

class. In such cases, the compiler requires each derived class to either define the function or redeclare

it as a pure virtual function. A class containing pure virtual functions cannot be used to declare any

object of its own. It is also known as “donothing” function.

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

virtual void display ( ) =0;

17) What is polymorphism?

Polymorphism is the ability to take more than one form. An operation may exhibit different behaviorsin different. The behavior depends upon the type of data used.

18)What are the types of polymorphism?

Basic Types

i)Runtime polymorphism

ii)Compile time polymorphism

Major Types

a.Run-time polymorphism

 b.Compile time polymorphismc.ad-hoc polymorphismd.Parametric polymorphism

e.Virtual functions

f.Function name overloading

g.Operator overloading

19)What is compile time polymorphism?

The overloaded member functions are selected for invoking by matching arguments both type

and number.This information is known to the compiler at the compile time and therefore compiler is

able to select the appropriate function for a particular call at the compile time itself.This is called

early binding or static binding or static linking.Also known as compile time polymorphism

20)What the types in compile time polymorphism?

a)Function overloading

 b)Operator overloading

21) What is RTTI?

Run-time type information (RTTI) is a mechanism that allows the type of an object to be

determined during program execution

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 25/33

22)List Out RTTI?

a)Base Type

 b)Compound Type

c)Container Type

23)Explain the other functions of RTTI

i)insert elements into the container 

ii)delete elements of the container 

iii)iterate through the elements of the container 

24)Explain the three parts of RTTI system

1)RTTI description of Base Types

2)Property Description of compound and container types

3)Property iterators

25)Write the purpose of typeid operator

The typeid operator provides a program with the ability to retrieve the actual derived type of 

the object referred to by a pointer or a reference.This operator is used along with the dynamic_cast

operator 

26)What is dynamic casting?Dynamic cast allows us to downcast a data type from one to a more specific one in the same

hierarchy

27)Define Downcasting

Downcasting is used to cast a pointer or reference to a base class to a derived

class.Downcasting is the opposite of the basic object-oriented rule,which states objects of a derived

class,can always be assigned to variables of a base class.Since base class variables can only

sometimes be assigned to variables of a derived class downcasting doesn’t always work 

28)Define Upcasting

Upcasting means classes can easily converge to a general class

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 26/33

PART-B

1) Discuss about polymorphism and its advantages.

2) Write a C++ program that will give the conditions of environment required,

food habits and unique characteristics of pet animals fish and dog. Define a

 base called pet that describe any common household pet; two derived classes called fish and dog

with items specific to that type of animals. Write pure virtual functions in the base class for 

operations that are common to both types of animals. Write a program to test the usage of classes.

3) Explain hybrid inheritance with suitable C++ coding

4) Define polymorphism. Explain the different types of 

 polymorphism

5) Write a C++ program using inheritance to implement the following.A newspaper agent pays two variant rates for the delivery of newspapers. A

delivery boy can earn RS. 2 on a morning delivery but only Rs. 1.50 on an eveningdelivery. Boys are salaried either for a morning delivery or for an evening paper round

 but not for both. Read(Input) the code for round (0 for morning and 1 for evening) and

the number of total paper rounds in one week done by a boy and compute his earning and

display it.

6) What are the different kinds of inheritance? Explain them with suitable examples

7) Briefly explain RTTI

8) Describe virtual function with suitable example

9) Define pure virtual function

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 27/33

UNIT V 9

Streams and formatted I/O – I/O manipulators - file handling – random access – object serialization – 

namespaces - std namespace – ANSI String Objects – standard template library.

1. What are streams?A Stream is a sequence of bytes. It can either as a source from which the input data can be

obtained or as a destination to which the output data can be sent

The stream source that provides data to the program is called the input stream and the

destination stream that receives output from the program is called output stream

2. What are the stream classes for console operations?

a)ios

 b)istrean

c)ostream

d)iostream

e)streambuf 

3) Draw the console stream classes for hierarchy

4) List out some of the unformatted I/O operators.a)put()

 b)get()c)getline()

d)write()

5) List out some of the formatted I/O operations

C++ supports a number of feature that could be used for formatting the output.These features

include

istream

ios

streambuf 

ostream

iostream

ostream_withassigniostream_withassignistream_withassign

Streambuf 

*bp=&strstreambase::

 bug

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 28/33

a)ios stream class member functions and flags

 b)Standard manipulators

c)User –defined manipulators

6) List some of the ios functions

a)width()

 b)precision()

c)fill()

d)setf()e)unsetf()

7) List some of the non-parameterized manipulators

a)dec

 b)hex

c)oct

d)es

e)endl

f)ends

g)flush

8) What is custom/user-defined manipulatorsThe users can design their own manipulators to control the appearance of the output

9)Write the syntax of creating a custom manipulator

Ostream & manipulator(ostream & output, arguments_if_any)

{

……

……(manipulator code)

……

Return output;

}

10) List out some of the manipulators

a)setw(int width)

 b)setprecision(int prec)

c)setfill(int fchar)

d)setbase(int base)

e)setiosflags(long flags)

f)resetioflags(long flags)

11) What are the flags that do not have bit fields?

a)ios::showbase-Use base indicator on output

 b)ios::showpos-Print + before positive integersc)ios::showpoint-Show trailing decimal point and zeros

d)ios::uppercase-Use uppercase letters for hex output

e)ios::unitbuf-Flush all streams after insertion

g)ios::stdio-Flush stdout and stderr after insertion

 

12) What are the two types of data communication?

a) Data transfer between the console unit and the program

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 29/33

 b) Data transfer between the program and disk file

13)Draw the stream classes for hierarchy

14)What are the functions that the file stream class provides?

a)seekg()-Moves get pointer to a specified location b)seekp()-Moves put pointer to a specified location

c)tellg()-Gives the current position of the get pointer 

d)tellp()-Gives the current position of the put pointer 

15) What is a file?

A file is a collection of related information defined by its creator. Files represent programs

(both source and object forms) and data.Data may be numeric,alphabetic, or alphanumeric.Files may

 be free-form,such as text files,or may be rigidly formatted.

16) List some of the file modes

1)ios::in

2)ios::out

3)ios::ate

4)ios::app

5)ios::trunk 6)ios::nocreate

7)ios::noreplace8)ios::binary

17) What is meant by namespace?

ANSI C++ Standard has added a new keyword namespace to define a scope that could hold

global identifiers.The best example of namespace scope is the C++ Standard Library.All

classes,functions and templates are declared within the namespace named std.

istream

ios

streambuf ostream

iostream filebuf  

ofstreamfstreamifstream

fstreambase

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 30/33

Using namespace std;

The using namespace statement specifies that the members defined in std namespace will be used

frequently throughout the program

18) Write the syntax for defining a namespace

namespace namespace_name

{//Declaration of 

//variables,functions,classes,etc.

}

19) What is unnamed namespaces?

An unnamed namespace is one that does not have a name. Unnamed namespace members

occupy global scope and are accessible in all scopes following the declaration in the file

20) What is Standard Template Library?

The collection of these generic classes and functions is called the Standard Template Library

21) List the components of STLThe STL contains several components. They are

1)Containers2)Algorithms

3)Iterators

22) What is container?

A container is an object that actually stores data.It is a way data is organized in memory. The

STL containers are implemented by template classes and therefore can be easily customized to hold

different types of data

23) What is an algorithm?

An algorithm is a procedure that is used to process the data contained in the containers. TheSTL includes many different kinds of algorithms to provide support to tasks such as initializing,

searching, copying, and sorting and merging

24) What is an iterator?

An iterator is an object that points to an element in a container. We can use iterators to move

through the contents of containers.Iterators are handled just like pointers

25)What are the three types of containers?

The STL contains three types of containers

1)Sequence containers

2)Associative containers

3)Derived containers

26) What is meant by sequence containers?

Sequence containers store elements in a linear sequence, like a line. Each element is related to

other elements by its position along the line. They all expand themselves to allow insertion of 

elements and all of them support a number of operations on them

Element0 Element1 Element2 ….. Last Element

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 31/33

27)What are the types of sequence containers

The STL provides three types of sequence containers

1)Vector 

2)list

3)deque

28) What is meant by Associative Containers?

Associative containers are designed to support direct access to elements using keys.

29) What are the types of Associative containers?

The STL provides three types of associative containers1)Set

2)Multiset

3)Map

4)Multimap

30) What is meant by Derived Containers?

The derived containers do not support iterators and therefore we cannot use them for 

data manipulation. They support two member functions pop() and push() for implementing deleting

and inserting operations.

31) What are the types of derived containers

The STL provides three types of derived containers

1)Stack 2)Queue

3)Priority_queue

32)What is meant by vector?

The vector stores elements in contiguous memory locations and enables direct access to any

element using the subscript operator[].A vector can change its size dynamically and therefore

allocates memory as needed at run time

33)What is meant by lists?

The list is another container that is popularly used. It supports a bidirectional, linear list and

 provides an efficient implementation for deletion and insertion operations.

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 32/33

34) What is meant by maps?

A map is a sequence of pairs where a single value is associated with each unique key.

Retrieval of values is based on the key and is very fast. We should specify the key to obtain the

associated value.

Value1

Value2

. .

. .

. .

. .

. .

.

. ValueN

35) Write the member functions of the map class  1) begin ()

2) clear()

3) empty()

  4) end()

5) erase()

6) find()

7) insert()

8) size()9) swap()

PART-B1) Write a program to write and read data in a file using object I/O functions write

( ) and read ( ). Declare class with data members name [2]

m int bill no, int _amount

debited and int received _ amount and in balance. Add 10 records and display the list of 

 persons with balances. The user should have a facility to modify the existing records

2) Describe the various file modes and its syntax

3) Write a C++ program to read from 2 files simultaneously.

4) What is file? Write the types of File access? Write an example program for sequential access

Key1

Key2

Key N

8/6/2019 Doc Cs2203oop2marks (1)

http://slidepdf.com/reader/full/doc-cs2203oop2marks-1 33/33

5) What is file? Write the types of File access? Write an example program for random access

6) What is standard template library? Write the types of STL?Write an example program for 

each STL types.