Available - Radiant

glintplainvilleSoftware and s/w Development

Nov 18, 2013 (3 years and 11 months ago)

102 views

ANS
-
1

(A)

STRUCTURED PROGRAMMING VS OBJECT ORIENTED PROGRAMMING

Task
-
centric vs. Data
-
centric

Structured programming is based around data structures and subroutines. The subroutines are where
stuff actually "happens", and the data structures are simply
containers for the information needed by
those subroutines.


Object oriented programming, on the other hand, shifts your primary focus to the data itself. Instead of
asking "what do I want to do and what will I need to know to do it", you ask "what kind of

things do I
want to have and what can those things do for me". Instead of designing your functions first and then
coming up with data structures to support them, you design types first and then come up with the
operations needed to work with them.

Similar
ities: Both require a rudimentary understanding of programming concepts and basic control flow.
Loops, conditional statements, and variables are concepts that are important whether you are using a
procedural language or an object oriented language.



Diffe
rences: Typically object oriented is viewed as more difficult. This is because an entirely different
problem solving approach must be taking. In addition, there are a variety of object
-
oriented
-
only
concepts such as classes and inheritance. For simple prog
rams, procedural is often preferred. The more
complicated the project, the easier it is to leverage the strengths of object oriented design.


A particular method

or family of methods that a software engineer might use to solve a problem is known as
a
methodology
. During the 1970s and into the 80s, the primary software engineering methodology was
structured programming
. The structured programming approach to progra
m design was based on the
following method:




To solve a large problem, break the problem into several pieces and work on each piece separately;



to solve each piece, treat it as a new problem that can itself be broken down into smaller problems;



repeat the
process with each new piece until each can be solved directly, without further decomposition.


This approach is also called
top
-
down

program design
.


The central concept of object
-
oriented progra
mming

is the
object
, which is a kind of module

containing data
and subroutines. An object is a kind of self
-
sufficient entity that has an
internal state

(the data it c
ontains)
and that can respond to
messages

(calls to its subroutines). A student
-
records object, for example, has a state

consisting of the details of all registered students. If a message is sent to it telling it to add the
details of a
new student, it will respond by modifying its state to reflect the change. If a message is sent telling it to print
itself, it will respond by printing out a list of details of all registered students.


The OOP

approach to software engineering is to begin by




identifying the objects involved in a problem;



identifying the messages

that those objects should respond to.


The solution that results is a collection of objects, each with its own
data and its own set of responsibilities. The
objects interact by sending messages

to each other.


ANS
-
1

(B)

Probably the best way to start learning a programming language is with a program. So here is our
first program:

// my first
program in C++


#include <iostream.h>


int main ()

{


cout << "Hello World!";


return 0;

}

Hello World!

The left side shows the source code for our first program, which we can name, for
example,

hiworld.cpp
. The right side shows the result of the progra
m once compiled and
executed. The way to edit and compile a program depends on the compiler you are using.
Depending on whether it has a Development Interface or not and on its version. Consult
section

compilers

and the manual or help included with your compiler if you have doubts on how
to compile a C++ console program.

The previous program is the first program that most programming apprentices write, and its
result

is the printing on screen of the "Hello World!" sentence. It is one of the simpler programs
that can be written in C++, but it already includes the basic components that every C++ program
has. We are going to take a look at them one by one:

// my first pr
ogram in C++

This is a comment line. All the lines beginning with two slash signs (
//
) are considered
comments and do not have any effect on the behavior of the program. They can be used
by the programmer to include short explanations or observations
within the source itself.
In this case, the line is a brief description of what our program does.

#include <iostream.h>

Sentences that begin with a pound sign (
#
) are directives for the preprocessor. They are
not executable code lines but indications for t
he compiler. In this case the
sentence

#include <iostream.h>

tells the compiler's preprocessor to include
the

iostream

standard header file. This specific file includes the declarations of the basic
standard input
-
output library in C++, and it is included
because its functionality is used
later in the program.

int main ()

This line corresponds to the beginning of the

main

function declaration. The

main

function
is the point where all C++ programs begin their execution. It is independent of whether it
is at
the beginning, at the end or in the middle of the code
-

its content is always the first
to be executed when a program starts. In addition, for that same reason, it is essential
that all C++ programs have a

main

function.

main

is followed by a pair of pare
nthesis

()

because it is a function. In C++ all functions
are followed by a pair of parenthesis

()

that, optionally, can include arguments within
them. The content of the

main

function immediately follows its formal declaration and it is
enclosed between c
urly brackets (
{}
), as in our example.

cout << "Hello World";

This instruction does the most important thing in this program.

cout

is the standard
output stream in C++ (usually the screen), and the full sentence inserts a sequence of
characters (in this ca
se "Hello World") into this output stream (the screen).

cout

is
declared in the

iostream.h

header file, so in order to be able to use it that file must be
included.

Notice that the sentence ends with a semicolon character (
;
). This character signifies the
end of the instruction and

must

be included after

every

instruction in any C++ program
(one of the most common errors of C++ programmers is indeed to forget to include a
semicolon

;

at the end of each instruction).

return 0;

The

return

instruction causes
the

main()

function finish and return the code that the
instruction is followed by, in this case

0
. This it is most usual way to terminate a program
that has not found any errors during its execution. As you will see in coming examples, all
C++ programs en
d with a sentence similar to this.

Therefore, you may have noticed that not all the lines of this program did an action. There were
lines containing only comments (those beginning by

//
), lines with instructions for the
compiler's preprocessor (those begin
ning by

#
), then there were lines that initiated the declaration
of a function (in this case, the

main

function) and, finally lines with instructions (like the call
to

cout <<
), these last ones were all included within the block delimited by the curly brac
kets
(
{}
) of the

main

function.

The program has been structured in different lines in order to be more readable, but it is not
compulsory to do so. For example, instead of

int main ()

{


cout << " Hello World ";


return 0;

}

we could have written:

int ma
in () { cout << " Hello World "; return 0; }

in just one line and this would have had exactly the same meaning.

In C++ the separation between instructions is specified with an ending semicolon (
;
) after each
one. The division of code in different lines
serves only to make it more legible and schematic for
humans that may read it.

Here is a program with some more instructions:

// my second program in C++


#include <iostream.h>


int main ()

{


cout << "Hello World! ";


cout << "I'm a C++ program";


return 0;

}

Hello World! I'm a C++ program

In this case we used the

cout <<

method twice in two different instructions. Once again, the
separation in different lines of the code has just been done to give greater readability to the
program, since

main

c
ould have been perfectly defined thus:

int main () { cout << " Hello World! "; cout << " I'm to C++ program "; return 0; }

We were also free to divide the code into more lines if we considered it convenient:

int main ()

{


cout <<


"Hello World!";


cout


<< "I'm a C++ program";


return 0;

}

And the result would have been exactly the same than in the previous examples.

Preprocessor directives (those that begin by

#
) are out of this rule since they are not true
instructions. They are

lines

read and

discarded by the preprocessor and do not produce any code.
These must be specified in their own line and do not require the include a semicolon (
;
) at the
end.

Comments.

Comments are pieces of source code discarded from the code by the compiler. They do
n
othing. Their purpose is only to allow the programmer to insert notes or descriptions
embedded within the source code.

C++ supports two ways to insert comments:

// line comment

/* block comment */

The first of them, the line comment, discards everything
from where the pair of slash signs (
//
)
is found up to the end of that same line. The second one, the block comment, discards
everything between the

/*

characters and the next appearance of the

*/

characters, with the
possibility of including several lines
.

We are going to add comments to our second program:

/* my second program in C++


with more comments */


#include <iostream.h>


int main ()

{


cout << "Hello World! ";
// says
Hello World!


cout << "I'm a C++ program";
// says I'm
a C++ program


return 0;

}

Hello World! I'm a C++ program

If you include comments within the sourcecode of your programs without using the comment
characters combinations

//
,

/*

or

*/
, the compiler will take them as if they were C++
instructions and, most likely causing

one or several error messages.



ANS
-
1

(C)

(i) SIZEOF OPERATOR

The

sizeof

is a keyword, but it is a compile
-
time operator that determines the size, in bytes, of a variable or data type.

The sizeof operator can be used to get the size of classes, structure
s, unions and any other user defined data type.

The syntax of using sizeof is as follows:

sizeof

(
data type
)

Where data type is the desired data type including classes, structures, unions and any other user defined data type.

Try the following example to understand all the sizeof operator available in C++. Copy and paste following C++ program in tes
t.cpp
file and compile and run this program.

#include

<iostream>

using

namespace

std
;



int

main
()

{


cout
<<

"Size of char : "

<
<

sizeof
(
char
)

<<

endl
;


cout
<<

"Size of int : "

<<

sizeof
(
int
)

<<

endl
;


cout
<<

"Size of short int : "

<<

sizeof
(
short

int
)

<<

endl
;


cout
<<

"Size of long int : "

<<

sizeof
(
long

int
)

<<

endl
;


cout
<<

"Size of float : "

<<

sizeof
(
float
)

<<

endl
;


cout
<<

"Size of double : "

<<

sizeof
(
double
)

<<

endl
;


cout
<<

"Size of wchar_t : "

<<

sizeof
(
wchar_t
)

<<

endl
;


return

0
;

}

When the above code is compiled and executed, it produces the following result, which can vary from machine to machine:

Size

of
char

:

1

Size

of
int

:

4

Size

of
short

int

:

2

Size

of
long

int

:

4

Size

of
float

:

4

Size

of
double

:

8

Size

of
wchar_t

:

4


(II)

LOGICAL OPERATOR

he

logical operators

are used to logically combine, compare Boolean conditions or expressions.

The
following table lists the operators.

Operator

Action

!

NOT

&&

AND

||

OR


Example:



#include <iostream.h>


using namespace std;


void main()


{


int date;


cout << "Enter the Date::";


cin >> date;


if ((date!=0)&&(date>10 && date
<20) )


{


cout << "Date is in the Middle of the Month" ;


}


else if (date<1 || date>31)


{


cout << "Enter a valid DATE";


}


else


{


cout << "Date is either the start or end of the Month";


}


}


Result:


Enter the Date:: 12


Date is in the Middle of the Month


(iii)

SCOPE RESOLUTION OPERATOR

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

C++ programming code

#include <iostream>



char

c
=

'a'
;

// global variable



int

main
()

{


char

c
=

'b'
;

//local variable




cout

<<

"Local c: "

<<

c
<<

"
\
n
"
;



cout

<<

"Global c: "

<<

::
c

<<

"
\
n
"
;

//using scope
resolution operator




return

0
;

}


Scope resolution operator in class

#include <iostream>



class

programming
{

public
:


void

output
()
;

//function declaration

}
;



// function definition outside the class



void

programming
::
output
()

{


cout

<<

"Function defined outside the class.
\
n
"
;

}



int

main
()

{


programming x
;


x.
output
()
;




return

0
;

}



ANS
-
2

(A)

#include<iostream.h>

#include<conio.h>

#include<string.h>

Class Book

{

Int ISBNNo;

Char
Title
[30];

Char Author[30];

Char pub[50];

Float
price;


Public: Book()


{



ISBNNO=1001;



Strcpy(Title,”C++ Programming”);



Strcpy(Author, “E.Balagurusamy”);



Strcpy(pub, “Tata Press”);



Price=300;


}



Void display_data()


{



Cout<<”Book ISBNNO”<<ISBNNO<<endl;



Cout<<”Book Title”
<<Title<<endl;



Cout<<”Book Author Name”<<Author<<endl;



Cout<<”Book Publisher”<<pub<<endl;



Cout<<”Book Price”<<price<<endl;


}

};


Main()

{

Book B;

B.display_data();

Getch();

}



(B)


(i)

ABSTRACTION


Data abstraction refers to, providing only essential
information to the outside word and hiding their background details, i.e., to
represent the needed information in program without presenting the details.

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

In C++, we use

classes

to define our own abstract data types (ADT). You can use the

cout

object of class

ostream

to stream data
to standard output like this:

#include

<iostream>

using

namespace

std
;


int

main
(

)

{


cout
<<

"Hello C++"

<
<
endl
;


return

0
;

}

Here, you don't need to understand how

cout

displays the text on the user's screen. You need to only know the public interface and
the underlying implementation of cout is free to change.

Access Labels Enforce Abstraction:

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



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



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

There are no restrictions on how often an access label may appear. Each access label sp
ecifies the access level of the succeeding
member definitions. The specified access level remains in effect until the next access label is encountered or the closing ri
ght brace
of the class body is seen.

Benefits of Data Abstraction:

Data abstraction prov
ides two important advantages:



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



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

By defining data members only in the private section of the class, the class author is free to make changes in the data. If t
he
implementation changes, only the class code needs to be examined to see what affect the change may
have. If data are public, then
any function that directly accesses the data members of the old representation might be broken.

Data Abstraction Example:

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

#include

<iostream>


class

Adder
{


public
:


// constructor


Adder
(
int

i
=

0
)


{


total
=

i
;


}


// interface to outside world


void

addNum
(
int

number
)


{


total
+=

number
;


}


// interface to outside world


int

getTotal
()


{


return

total
;


};


private
:


// hidden data from outside world


int

total
;

};

int

main
(

)

{


Adder

a
;




a
.
addNum
(
10
);


a
.
addNum
(
20
);


a
.
addNum
(
30
);



cout
<<

"Total "

<<

a
.
getTotal
()

<<
endl
;


return

0
;

}

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

Total 60

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

addNum

and

getTotal
are the interfaces to the
outside world and a user needs to know them to use the class. The private member

total

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



Designing Strategy:

Abstraction
separates code into interface and implementation. So while designing your component, you must keep interface
independent of the implementation so that if you change underlying implementation then interface would remain intact.

In this case whatever program
s are using these interfaces, they would not be impacted and would just need a recompilation with the
latest implementation.


(ii)


ENCAPSULATION


Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manip
ulate the data, and
that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of

data hiding
.

Data encapsulation

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

data abstraction

is a mechanism of
exposing only the interfaces and hiding the implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of user
-
defined types, called

classes
. We
already have studied that a clas
s can contain

private, protected

and

public
members. By default, all items defined in a class are
private. For example:

class

Box

{


public
:


double

getVolume
(
void
)


{


return

length
*

breadth
*

height
;


}


private
:


double

length
;

// Length of a box


double

breadth
;

// Breadth of a box


double

height
;

// Height of a box

};

The variables length, breadth, and height are

private
. This means that they can be accessed only by other members of the Box
class, and not by any other part of your program. This is one way encapsulation is achieved.

To make parts of a class

public

(i.e., accessible to other parts of your program), you must declare them after the

public

keyword.
All variables or functions defin
ed after the public specifier are accessible by all other functions in your program.

Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to keep as ma
ny
of the details of each class hidden from al
l other classes as possible.

Data Encapsulation Example:

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

#include

<iostream>

using

namespace

std
;


class

Adder
{


public
:


// constructor


Adder
(
int

i
=

0
)


{


total
=

i
;


}


// interface to outside world


void

addNum
(
int

number
)


{


total
+=

number
;


}


// interface to outsid
e world


int

getTotal
()


{


return

total
;


};


private
:


// hidden data from outside world


int

total
;

};

int

main
(

)

{


Adder

a
;




a
.
addNum
(
10
);


a
.
addNum
(
20
);


a
.
addNum
(
30
);



cout
<<

"Total "

<<

a
.
getTotal
()

<<
endl
;


return

0
;

}

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

Total 60

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

addNum

and

getTotal
are

the interfaces to the
outside world and a user needs to know them to use the class. The private member

total

is something that is hidden from the
outside world, but is needed for the class to operate properly.

Designing Strategy:

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

encapsulation
.

This wisdom is applied most frequently to data members, but it applies equally to all members, including virtual functi
ons.



(III)

Operator Overloading


In C++ the overloading principle applies not only to functions, but to operators too. That is, of
operators can be extended to work not just with built
-
in types but also

classes
. A programmer can
provide his or her own operator to a class by overloading the built
-
in operator to perform some specific
computation when the operator is used on objects of that cla
ss. Is operator overloading really useful in
real world implementations? It certainlly can be, making it very easy to write code that feels natural
(we'll see some examples soon). On the other hand, operator overloading, like any advanced C++
feature, make
s the language more complicated. In addition, operators tend to have very specific
meaning, and most programmers don't expect operators to do a lot of work, so overloading operators
can be abused to make code unreadable. But we won't do that.







program

showing the

overloading

of


Assignment operators

in c++.

#include<iostream.h>

#include<conio.h>

Class sample

{

Private:

Int x, y;

Public:

Void getdata ()

{

Cout <<”
\
n enter the value of x and y”;

Cin>> x>>y;

}

Void operator = (sample obj)

{

X= obj.x;

Y=
obj.y;

}

Void display ()

{

Cout<<”
\
n value of x”<<x;

Cout<<”
\
n value of y”<<y;

}

};

Void main ()

{

Sample obj1, obj2;

Obj1.getdata ();

Obj1.display ();

Obj2=ob1;

Obj2.display();

getch ();

}


(iv)

STATIC MEMBER

We can define class members static using

static

keyword. When we declare a member of a class as static it means no matter how
many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized t
o zero when the first object is created, if no other
initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the

following
example by redeclaring the static variable, using the scope resolut
ion operator

::

to identify which class it belongs to.


Static Function Members:

By declaring a function member as static, you make it independent of any particular object of the class. A static member func
tion
can be called even if no objects of the class

exist and the

static

functions are accessed using only the class name and the scope
resolution operator

::
.

A static member function can only access static data member, other static member functions and any other functions from outsi
de
the class.

Static m
ember functions have a class scope and they do not have access to the

this

pointer of the class. You could use a static
member function to determine whether some objects of the class have been created or not.


#include<iostream.h>

#include<conio.h>

class

stat

{


Static int

count;


int

no;


public
:


void

cnt()


{


cout<<
"Count = "
<<count<<endl;


count++;


}


void

num()


{


no=1;


cout<<
"Number is = "
<<no<<endl;



}

};

int

stat::count=1;


main()

{


clrscr();


stat d,e;


for
(
int

i=0;i<5;i++)


{


d.cnt();


e.num();


}

}



ANS
-
3

(A)

Polymorphism

:

'Polymorphism' is an object oriented term. Polymorphism may be defined as the
ability of related objects to respond to the same message with different, but appropriate actions.



In other words, polymorphism means taking more than one form. Polymorphism l
eads to two
important aspects in Object Oriented terminology


Function Overloading and Function
Overriding. Overloading is the practice of supplying more than one definition for a given function
name in the same scope. The compiler is left to pick the app
ropriate version of the function or
operator based on the arguments with which it is called. Overriding refers to the modifications
made in the sub class to the inherited methods from the base class to change their behavior.




Polymorphism is broadly
divided into two parts:





Static polymorphism



exhibited by overloaded functions.



Dynamic polymorphism



exhibited by using late binding.



Static Polymorphism



Static polymorphism

refers to an entity existing in different physical forms simultaneously.
Static
polymorphism involves binding of functions based on the number, type, and sequence of
arguments. The various types of parameters are specified in the function declaration, and
therefore the function can be bound to calls at compile time. This form o
f association is
called

early binding
. The term

early binding

stems from the fact that when the program is
executed, the calls are already bound to the appropriate functions.



The resolution of a function call is based on number, type, and sequence of arg
uments declared
for each form of the function. Consider the following function declaration:





void add(int , int);



void add(float, float);



When the

add()

function is invoked, the parameters passed to it will determine which versio
n of
the function will be executed. This resolution is done at compile time.

Example:
-

#include<iostream.h>

#include<stdlib.h>

#include<conio.h>

Class calc

{

Public void show(int a)

{

Cout<<a;

}


Public void show(int a, int b)

{

Cout<<a<<b;

}


Public void show(int a,int b,int c)

{

Cout<<a<<b<<c;

}

};


Void main()

{

Calc obj;

Obj.show(10);

Obj.show(10,20);

Obj.show(10,20,30);

}






Dynamic Polymorphism



Dynamic polymorphism

refers to an entity changing its form depending on the circumstances. A

function is said to exhibit dynamic polymorphism when it exists in more than one form, and calls
to its various forms are resolved dynamically when the program is executed. The
term

late

binding


refers to the resolution of the functions at run
-
time inste
ad of compile time.
This feature increases the flexibility of the program by allowing the appropriate method to be
invoked, depending on the context.

Example:

#include

<iostream>

using

namespace

std
;

class

B

{


public:


virtual

void

display
()

/* Virtual function */


{

cout
<<
"Content of base class.
\
n"
;

}

};


class

D1
:

public

B

{


public:


void

display
()


{

cout
<<
"Content of first derived class.
\
n"
;

}

};


class

D2
:

public

B

{


public:


void

display
()


{

cout
<<
"Content of second derived class.
\
n"
;

}

};


int

main
()

{


B
*
b
;


D1 d1
;


D2 d2
;


/* b
-
>display(); // You cannot use this code here because the function of base class
is virtual. */



b
=

&
d1
;


b
-
>
display
();

/* calls display() of
class derived D1 */


b
=

&
d2
;



b
-
>
display
();

/* calls display() of class derived D2 */


return

0
;

}

Output

Content of first derived class.

Content of second derived class.



Static Vs Dynamic Polymorphism



Static polymorphism is considered more efficient, and dynamic polymorphism more flexible.



Statically bound methods are those methods that are bound to their calls at compile time.
Dynamic function calls are bound to the functions during run
-
time. This in
volves the additional
step of searching the functions during run
-
time. On the other hand, no run
-
time search is required
for statically bound functions.

As applications are becoming larger and more complicated, the need for flexibility is increasing
rapidl
y. Most users have to periodically upgrade their software, and this could become a very
tedious task if static polymorphism is applied. This is because any change

in requirements requires a major modification in the code. In the case of dynamic binding, th
e
function calls are resolved at run
-
time, thereby giving the user the flexibility to alter the call
without having to modify the code.



(B)

Friend Functions

A C++ friend functions are special functions which can access the private members of a class. The
y are
considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make
them useful in certain cases.

For instance: when it is not possible to implement some function, without making
private members accessible in
them. This situation arises mostly in case of operator overloading.

In the following example, the friend function print is a member of class TWO and accesses the private data
members a and b of class ONE.


#include

<iostream>

using

namespace

std;


//Must

be

known

to

TWO

//before

declaration

of

ONE.

class

ONE;


class

TWO

{

public:


void

print(ONE&

x);

};


class

ONE

{


int

a,

b;


friend

void

TWO::print(ONE&

x);

public:


ONE()

:

a(1),

b(2)

{

}

};


void

TWO::print(ONE&

x)

{


cout

<<

"a

is

"

<<

x.a

<<

endl
;


cout

<<

"b

is

"

<<

x.b

<<

endl;

}


int

main()

{


ONE

xobj;


TWO

yobj;


yobj.print(xobj);

}


Friend functions have the following properties:



1) Friend of the class can be member of some other class.



2) Friend of one class can be friend of another
class or all the classes in one program, such a friend is
known as GLOBAL FRIEND.



3) Friend can access the private or protected members of the class in which they are declared to be friend,
but they can use the members for a specific object.



4) Friends are

non
-
members hence do not get “this” pointer.



5) Friends, can be friend of more than one class, hence they can be used for message passing between the
classes.



6) Friend can be declared anywhere (in public, protected or private section) in the class.


ADVA
NTAGES


when a data

is declared as private inside a class, then it is not accessible from outside

the class. A function that
is not a member or an external class will not

be able to access the private data. A programmer may have a
situation where

he or she

would need to access private data from non
-
member functions and

external classes.
For handling such cases, the concept of Friend functions

is a useful tool.



ANS
-
4

(A)

seekp()

Sets the position of the put pointer in any location in output mode file.

ostream & seekp(long);

ostream & seekp(long,seek_dir);

Seeking direction. It is an object of type

ios_base::seek_dir

that specifies an absolute position
from where the offset parameter is applied.


seek_dir

takes the definition of

enum seek_dir {beg, cur,
end };
.


value

offset is relative to...

ios_base::beg

beginning of the stream buffer

ios_base::cur

current position in the stream buffer

ios_base::end

end of the stream buffer

Example



// position in output stream

#include <fstream>

// std::ofstream
















int

main () {



std::ofstream outfile;


outfile.open (
"test.txt"
);



outfile.write (
"This is an apple"
,16);


long

pos = outfile.tellp();


outfile.seekp (pos
-
7);


outfile.write (
" sam"
,4);



outfile.close();



return

0;

}

OUTPUT
-

this is sample


seekg()

Sets the position of the get pointer in any location in input mode file.

(1)

istream& seekg (streampos pos);

(2)

istream& seekg (streamoff off, ios_base::seekdir way);

Parameters

pos

New absolute position within the stream

(relative to the beginning).

streampos

is an

fpos

type (it can be converted to/from integral types).

off

Offset value, relative to the

way

parameter.

streamoff

is an offset type (generally, a signed integral type).

way

Object of type

ios_base::seekdir
. It may take any of the following constant val
ues:


value

offset is relative to...

ios_base::beg

beginning of the stream

ios_base::cur

current position in the stream

ios_base::end

end of the stream

Example







// read a file into memory

#include <iostream>
// std::cout

#include <fstream>
// std::ifstream


int

main () {


std::ifstream is (
"test.txt"
, std::ifstream::binary);























if

(is) {


// get length of file:


is.seekg (0, is.end);


int

length = is.tellg();


is.seekg (0, is.beg);



// allocate memory:


char

* buffer =
new

char

[length];



// read data as a block:


is.read (buffer,length);



is.close();



// print content:


std::cout.write (buffer,length);



delete
[] buffer;


}



return

0;

}


Tellg()

streampos tellg();

Get
position in input sequence

Returns the position of the current character in the input stream.


Example























// read a file into memory

#include <iostream>
// std::cout

#include <fstream>
// std::ifstream


int

main () {


std::ifstream is (
"test.txt"
, std::ifstream::binary);


if

(is) {


// get length of file:


is.seekg (0, is.end);


int

length = is.tellg();


is.seekg (0, is.beg);



// allocate memory:


char

* buffer =
new

char

[length];



// read
data as a block:


is.read (buffer,length);



is.close();



// print content:


std::cout.write (buffer,length);









delete
[] buffer;


}



return

0;

}


Tellp()

streampos tellp();

Get position in output sequence

Returns the position of the
current character in the output stream


// position in output stream

#include <fstream>
// std::ofstream


int

main () {



std::ofstream outfile;


outfile.open (
"test.txt"
);



outfile.write (
"This is an tellp exam
ple"
,16);


long

pos = outfile.tellp
();


outfile.seekp (pos
-
7);


outfile.write (
" sam"
,4);



outfile.close();



return

0;

}


ANS
-
4

(B)

Exceptions are situations which must be avoided during program executions. Exceptions are caused by errors,
invalid inputs or invalid processing. Excepti
ons can lead to either program termination or generating
unexpected outputs.

In general, it is assumed that exceptions are errors but this is not always true. We can state:

All

errors

are

exceptions

but

not

necessarily

all

exceptions

are

errors.

Exceptions

can be handled or avoided by a simple control statement such as an if
-
else statement, but most
languages provide a separate mechanism of exception handling.

Exception Handling

Exception handling is a process of handling exceptional situations that may occ
ur in a program due to the
above stated reasons in such a way that:



The program will terminate gracefully i.e. it will give a proper message and then will terminate the
program.



After giving the proper message stating the reason of the exception the progra
m continues to execute after
correcting the error.

In the C++ language, exception handling is performed using the following keywords:



try



catch



throw



throws

Take a look at the process of exception handling:

To catch exceptions we must place a portion of co
de under exception inspection. We can do this by putting that
portion of code in a try block. So, when an exceptional circumstance arises (within that block) an exception is
thrown. This in turn transfers the control to the exception handler. If there are
no exceptions thrown, the code
will continue normally and all handlers are ignored.

Take a look at an example:



#include<iostream>


using

namespace

std;



int

main

()


{



try



{




throw

5;



}




catch

(int

a)



{




cout

<<

"An

exception

occurred!"

<<

endl;




cout

<<

"Exception

number

is:

"

<<

a

<<

endl;



}



return

0;


}


Standard exceptions

The C++ standard library provides a base class specifically designed to declare objects to be thrown as
exceptions. To make use of the standard exceptions we
have to include the exception header file.

All of the exceptions thrown by parts of the C++ Standard library will throw exceptions derived from the
std::exception class. These exceptions are:

bad_alloc

A bad_alloc is thrown by new if an allocation failure
occurs.

bad_cast

A bad_cast is thrown by dynamic_cast when it fails with a referenced type.

bad_exception

A bad_exception is thrown when an exception type doesn’t match any catch

bad_typeid

A bad_typeid is thrown by typeid

ios_base::failure

An ios_base::fa
ilure is thrown by functions in the iostream library.

ANS
-
5

(A)

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particul
ar
type.

A template is a blueprint or formula for creating a generi
c class or a function. The library containers like iterators and algorithms are
examples of generic programming and have been developed using template concept.

Function templates

Function templates are special functions that can operate with

generic types
.

This allows us to create a function
template whose functionality can be adapted to more than one type or class without repeating the entire code for
each type.


In C++ this can be achieved using

template parameters
. A template parameter is a special kind
of parameter that
can be used to pass a type as argument: just like regular function parameters can be used to pass values to a
function, template parameters allow to pass also types to a function. These function templates can use these
parameters as if th
ey were any other regular type.

Class templates

We also have the possibility to write class templates, so that a class can have members that use template
parameters as types

//stack using templates

#include<iostream.h>

#include<iomanip.h>

template<
class

s>

///templats class
class

stack

{


private
:


int

top;


s item;


s array[5];


public
:


stack()


{


top=
-
1;


}


void

getdata()


{


cout<<
"enter item to push in stack"
<<endl;


cin>>item;




}


void

push()


{


if
(top==5)


cout<<
"overflow"
<<endl;


else


{



top++;


array[top]=item;


}


}


void

pop()


{


if
(top==
-
1)


cout<<
"underflow"
<<endl;


else


{


array[top]=NULL;




top
--
;


}


}


void

disp()


{


for
(
int

i=0;i<=top;i++)


{


cout<<array[i]<<
'
\
t'
;


}


cout<<endl;



}

};

int

main()

{


stack<
int
>stacki;


stack<
char
>stackc;


int

r;


char

ch;


do


{


cout<<
"integer array"
<<endl;


cout<<
"press 1 to push element in stack & 2 to pop it"
<<endl;


cout<<
" 3 to display stack"
<<end
l;


cin>>r;


switch

(r)


{


case

1:


stacki.getdata();


stacki.push();


break
;


case

2:


stacki.pop();


break
;


case

3:


stacki.disp();


break
;


default
:


cout<<
"bad input"
<<endl;


break
;


}


cout<<
"do you want to process more y/n"
<<endl;


cin>>ch;


}


while
(ch!=
'n'
);

do

{


cout<<
"character array"
<<endl;


cout<<
"press 1 to push element in stack & 2 to pop it"
<<endl;


cout<<
" 3 to display stack"
<<endl;


cin>>r;


switch

(r)


{


case

1:


stackc.getdata();


stackc.push();


break
;


case

2:


stackc.pop();


break
;


case

3:


stackc.disp();


break
;


default
:


cout<<
"bad input"
<<endl;


break
;


}


cout<<
"do you want to process more y/n"
<<endl;


cin>>ch;


}


while
(ch!=
'n'
);



return

0;

}


ANS
-
5

(B)

One of the most important concepts in object
-
oriented programming is that of inheritance. Inheritance allows us to
define a class in
terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reu
se the
code functionality and fast implementation time.

When creating a class, instead of writing completely new
data members and member functions, the programmer can designate that
the new class should inherit the members of an existing class. This existing class is called the

base

class, and the new class is
referred to as the

derived

class.

Types of Inheritance

1.

Single Inheritance


In this type of inheritance one derived class inherits from only one base class.
It is the most simplest form of Inheritance.
<


2. Multiple Inheritance


In this type of inheritance a single derived class may inherit from two or more
than two base classes.


3.
Hierarchical Inheritance


In this type of inheritance, multiple derived classes inherits from a single base
class.


4.
Multilevel
Inheritance


In this type of inheritance the derived class inherits from a class, which in
turn inherits from some other class. The Super class for one, is sub class for
the other.


5.
Hybrid Inheritance


Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.

Advantages:
-



One of the key benefits of inheritance is to minimize the amount of duplicate code in an application
by sharing common


code

amongst several subclasses. Where equivalent code exists in two
related classes, the hierarchy can usually be


refactored to move the common code up to a mutual
superclass. This also tends to result in a better organization of


code and smaller, simpler
c
ompilation units.



Inheritance can also make application code more flexible to change because classes that inherit
from a common


superclass can be used interchangeably. If the return type of a method is
superclass


Reusability
--

facility to use public m
ethods of base class without rewriting the same

Extensibility
--

extending the base class logic as per business logic of the derived class

Data hiding
--

base class can decide to keep some data private so that it cannot be altered by the
derived class


Ove
rriding
--
With inheritance, we will be able to override the methods of the base class so that
meaningful


implementation of the base class method can be designed in the derived class.