QUAN-C

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 80

C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

TOPIC : OPERATORS, KEYWORD, IDENTIFIER, VARIABLES

--------------------------------------
Short Answer Questions
--------------------------------------

Q. Simplify the following code:


bool inside = !((x < left) || (x > right) || (y < top) || (y > bottom);

Ans:

Bool or Boolean type variable is not supported in Borland / Turbo C++.


Howe’er, the following code works in Dev C++ compiler.

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

int main()
{
bool x = 4, y = 5;
int left = 5, right = 2, top = 1, bottom = 3;
bool inside = !((x<left) || (x>right) || (y<top) || (y>bottom));
cout<<endl<<x<<endl;
getch();
}
//Output : 0

Q. What do you understand by pointer’s arithmetic?


Ans:
Pointer Arithmetic provides the following utilities:
1. A pointer variable can be assigned to an ordinary variable.
2. A pointer variable can be assigned to another pointer variable.
3. A pointer variable can be assigned ‘NULL’ [ i.e., 0 ].
4. Integer quantity can be added or subtracted from a pointer variable.
5. Two pointer variables can be compared.
6. Two pointer variables cannot be added or subtracted from a pointer variable.

Q. Consider the following section of C++ program, in which a and b are int variables
b = 2;
a = 1;
a = b++;

What are the values of a and b?


Ans:

The value of a will be 2 and the value of b will be 3.

Explanation :
Here the initial value of a is 1 and the last statement is a = b++;
So, this is the post increment of the variable b. Therefore, the value of the variable b, 2 will assign
first to the variable a and then b will be incremented to the value 3.

1
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Explain nesting of structures with a suitable example.


Ans:
Nesting of structure means the structure with in a structure. structure is a user defined data
type, so once the user defines it he can use it just like any other data type, like in our struct
we have 2 variables of type char and int, similarly we can add another variable of some
structure data type. Suppose there was another structure called employee, then we could say

struct employee
{
int empId;

}

then

struct data
{
employee e; //structure within structure
int age;
...
}

Q. What is a scope resolution operator?


Ans:
The scope resolution operator is used to qualify hidden names so that they can be used anytime. The
scope resolution operator is used along with the class name in the header of the function definition.
It identifies the function as a member of a particular class. The unary scope operator can be used if a
namespace scope or global scope name is hidden by an explicit declaration of the same name in a
block or class.

For example, a member function is defined outside the class using the :: (double colon symbol)
scope resolution operator. The general syntax of the member function of a class outside its scope is:

<return_type> <class_name> :: <member_function> (arg1, arg2, …. , argN)

The type of member function arguments must exactly match with the types declared in the class
definition of the <class_name>.

Q. What is a reference variable?


Ans:
C++ uses a type of variable called a "reference" variable (or simply a "reference"). Reference
variables are basically pointers by another name (but may not be instantiated as such by the
compiler). It is possible to declare a reference within a function, like other variables. References are
designed to be used as parameters (arguments) to functions, e.g.,

#include <iostream.h>
void f(int&);
void main(void)
{
int i = 3;
f(i);
cout << i;
}

2
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void f(int& r)
{
r = 2*r; //r is ref. variable
}

The above program prints "6" (2*r doubles the value of the variable referenced by r, namely, i).

Q. What is a type cast operator?


Ans:
Converting an expression of a given type into another type is known as type-casting. The task of
type-casting of variables or expressions is done by using some operators known as type cast
operators.

The type cast operators are used as the following syntax:


type name(expression)

For example:
average = sum / float(i);

Q. What is endL manipulator?


Ans :
The endL manipulator indicates the end of a specified statement. It produces a new line character, in
the same way as the insertion of '\n' does, but with an additional feature that is when it is used with
buffered streams, the buffer is flushed.
For example :
cout<<"First sentence."<< endl;
cout<<"Second sentence."<< endl;

would print out :


First sentence.
Second sentence.

Q. Write a deceleration for main() that will enable command line arguments.
Ans:
int main( int argc, char *argv[])
{
if(argc != 2)
{
cout<<”You forgot to type your name.\n”;
}
else
{
cout<<”Hello,”<<argv[1];
}
return 0;
}

Q. Enumerate the rules of identifiers.


Ans:
The rules of identifiers are as follows:

1. Only alphabetic characters, digits and underscores are permitted.


2. The name cannot start with a digit.
3. Uppercase and lowercase letters are distinct
4. A declared keyword cannot be used as a variable name.

3
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Name the header file of C++ to which built-in function gets() and getx() belong to.
Ans:

As far as Turbo C++ is concerned, there is no such function that can return two values such as co-
ordinates of x & y, so getxy() is absurd.

Function Name Header File


gets() stdio.h
getx() or gety() graphics.h
gotoxy() conio.h

Q. What do you mean by ‘#include’ and ‘#define’?


Ans:
‘#include’ and ‘#define’ are the preprocessor directives. Preprocessor directives are lines included
in the code of the program that are not programming statements but directives for the preprocessor.
These lines are always preceded by a hash sign(#). The preprocessor is executed before the actual
compilation of code begins, therefore the preprocessor digests all these directives before any code is
generated by the statements.

These preprocessor directives extend only across a single line of code. As soon as a newline
character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at
the end of a preprocessor directive. The only way a preprocessor directive can extend through more
than one line is by preceding the newline character at the end of the line by a backslash(\).

Q. What are the various data conversion available?


Ans:

There are two types of data conversion.

1) Upper type conversion


In upper type conversion, the data, containing short memory space is converted to the data,
containing larger memory spaces.
E.g, int a = 10;
float b = (float) a;
Here integer a is converted to a floating number.

2) Lower type conversion


In lower type conversion, the data, containing large memory space is converted to the data,
containing shorter memory spaces.
e.g, float a = 10.25;
int b = (int)a;

Here float, a is converted to an integer, but after conversion the fractional part of the variable
will lost. And this is the major pitfall of data conversion. To avoid the loss of data we should
not use the lower conversion.

Q. What is a structure variable?


Ans:
A structure variable definition contains an optional storage class keyword, the struct keyword, a
structure tag, a declarator, and an optional identifier. The structure tag indicates the data type of the
structure variable. Structures can be declared having any storage class.
Structures declared with the register storage class specifier are treated as automatic structures.

4
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

E.g.
struct
{ char name[35];
int roll;
float total_marks;
}student;

To declare a structure variable : struct student s1, s2, s3;

Q. What do you understand by memory leaks?


Ans:
A memory leak happens when we forget to free a block of memory allocated with the ‘new’
operator/constructor or when it is impossible to do so for the compiler. As a consequence the
application may eventually run out of memory and may even cause the system to crash.
As a preventive measure to this, we should use delete operator & also can invoke the destructor at
appropriate positions(i.e. when & where some data-type/variable is no longer needed).

Q. How would you typedef a class to some simple name?


Ans:

Let us consider a class or structure is declared with a name salary_bonus_bills as follows


struct salary_bonus_bills
{
int sal, bns, bill, total;
void cal() ;
}
Then it is very tough to handle a name like salary_bonus_bills with in the program.
So, we can give some simple name to the class. Now, if I want to rename the class
salary_bonus_bills with a short name sbb then we have to add a single line to do it very easily as
following :
typedef salary_bonus_bills sbb

Q. How many ways are there to initialize an int with a constant?


Ans:

There are two formats for initializers in C++ as shown in the example that follows. The first format
uses the declaration with initialization. The second format uses declaration & initialization in
separate steps.

(1) int foo = 123;

(2) int foo;


foo = 123;

Q. If a = 5, b = 10, c = 15 and d = 0, what is the truth value of the following expression?


a+d>=c–b
Ans:

The value of the expression (a+d) is 5+0=5 and the value of the expression (c-b) is 15-10 = 5. So
the whole expression implies 5>=5, which is true. Hence the expression will return the truth value,
1.

5
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Define an identifier in C++.


Ans:
In C++, Identifiers refer to the names of variables, arrays, classes, etc., created by the programmers.
Identifiers are the fundamental requirement of any language. Each language has its own rules for
naming these identifiers. C++ follows the below given rules for naming identifiers:

 Only alphabetic characters, digits and underscores are permitted.


 The name cannot start with a digit.
 Uppercase and Lowercase letters are distinct.
 A declared keyword cannot be used as a variable name.

Special care should be taken while naming a variable that is being shared by more than one file
containing C++ programs.

Examples of identifiers are GetData, sum_10numbers, etc.

Q. What is a keyword? List four keywords in C++.


Ans:
In C++, a keyword implements specific language feature. Keywords are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined program
elements.

Among numerous keywords in C++, the four keywords are: class, integer, register, try.

Q. How will you declare a constant in C++?


Ans:
In C++, a constant is declared like a variable but adding ‘const’ before it. It is needed to initialize
immediately in the constructor because one cannot set the value later as that would be altering it.
For example,
const int Constant1 = 96;

will create an integer constant, say, Constant1, with the value 96.

A constant also works with pointers but one has to be careful where ‘const’ to determine whether
the pointer or what it points to is constant or both.
For example,
const int * Constant2
declares that ‘Constant2’ is variable pointer to a constant integer.

Q. Define global variables.


Ans:
The scope for variables is determined by the place of their declaration. If a variable declaration
appears outside all the functions, i.e., outside a block, it is said to be ‘global variable’. A global
variable is available to all the functions and blocks defined in the file. A global variable comes into
existence when the program execution starts and is only destroyed when the program terminates.
Global variables hold their values throughout the program execution. Any expression may access
them regardless of what block of code that expression is in. They can be accessed from anywhere in
the file.

#include<iostream.h>
#include<conio.h>
int a;
void fun(void)
{
a++;

6
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

cout<<a<<endl;
}
int main(void)
{
int p=10;
clrscr();
a=p*2;
fun( );
}
Here the variable ‘a’ is global. And it can be accessed from both the main() and the
function sub() too.

Q. What is user defined data type?


Ans:
User defined data types in C++ are the data types created by the programmers using basic data types
to satisfy the requirements of the program. Some common user-defined data types are ‘Structures &
Classes’ and ‘Enumerated’ data types.

Structures & Classes: C++ allows to define an user-defined data type known as ‘class’, which can
be used, 0just like any other basic data type, to declare variables. The class variables are known as
objects, which are the central focus of object-oriented programming.

Enumerated Data Type: An enumerated data type is another user-defined type which provides a
way for attaching names to numbers, thereby increasing comprehensibility of the code. The enum
keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on. This
facility provides an alternative means for creating symbolic constants.
For example, enum color {red, blue, green, yellow};
C++ also provides ways to create anonymous enums (i.e., enums without tag names).
For example, enum {off, on}. Here, off is 0 and on is 1. These constants may be referenced in the
same manner as regular constants.

Q. How are the pointer variables declared in C++? Give an example.


Ans:
Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to
specify in its declaration which data type a pointer is going point to. Pointing to a char is not the
same as pointing to an int or a float.
The declaration of pointers follows the below given format:
type *name;

where ‘type’ is the data type of the value that the pointer is intended to point to. This type is not
the type of the pointer itself, but the type of the data the pointer points to.

The asterisk sign (*) that is used while declaring a pointer only indicates that it is a pointer (it is
part of its type compound specifier), and should not be confused with the dereference operator,
which is also written with an asterisk (*).

Examples of pointer variables:


int * number;
char * character;
float * greatnumber;

These are three declarations of pointers. Each one is intended to point to a different data type, but in
fact all of them are pointers and all of them will occupy the same amount of space in memory (the
size in memory of a pointer depends on the platform where the code is going to run). However, the
data to which they point to neither occupy the same amount of space nor are of the same type; the

7
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

first one points to an int, the second one to a char and the last one to a float. Therefore,
although these three example variables are all of them pointers which occupy the same size in
memory, they are said to have different types:
int*, char* and float* respectively, depending on the type they point to.

Q. Define instance variables.


Ans:
In C++, a class has a set of named data elements, known as its instance variables. The data elements
and methods that make up a class are called its members.

In object-oriented programming with classes, an instance variable is a variable defined in a


class, for which each object in the class has a separate copy. The instance variable is just
the opposite of class variable(which is a shared variable across all members of a class).
Separate instances of this variables are created with each objects created.

Example:
class Test
{
int a;
float b;
};

Here a and b are the instance variables. That means, when an object of class test will be
created, then the for each and every object of the class test, the variables a and b will be
created.

To access the instance variables use generally use .(dot) operator.


E.g. For an object T1 of class Test, the variable b can be accessed as : T1.b = 125.36;

Q. Explain enumeration with suitable examples.


Ans:
The enum(enumeration) is a user-defined type consisting of a set of enumerators(i.e., named integer
constants). It allows the user to define the range of values for the type.

The enum is declared as:


enum enum-type-name { enum-list } enum-variable;

For example:

enum e_friends
{
Anne,
Bunty,
Danny,
Gullu,
James,
Lalit
Mary,
Rita,
Sania
};

8
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

After declaration, it is possible to use enum-type-name as user-defined type. Enumeration variable


or constant may take on only values from enum-list.
Enumerators are stored by compiler as an integers: by default, first enumerator is 0, next enumerator
value is previous enumerator value + 1. When defining enumeration it is possible to specify integer
constant for every enumerator, say, Anne = 4, Bunty = 5, and so on.. in the above declaration, and
subsequent values that are not assigned a value will be incremented.

Q. Consider the following section of C++ program, in which i and n are int variables
n = 7;
i = 4;
i = n++;

What are the values of i and n?


Ans:

The value of n will be 8 and the value of i will be 7.


Explanation:
Here the initial value of n is 7 and the last statement is i = n++;
So, this is the post increment of the variable n. Therefore, the value of the variable n, 7 will assign
first to the variable i and then n will be incremented to the value 8.

Q. If a = 2, b = 1, c = 5 and d = 10, what is the truth-value of the following expression?


a = = d/c || d > c.
Ans:
The truth-value of the expression is 1.
Here the value of c is 5 and the value of d is 10, therefore the expression will be as
a = = 10/5||10>5
a = = 2 || 1 [because 10>5 is true and return 1]
2 = = 2 || 1 [because the value of a is 2 ]
1 || 1 [ 2 = = 2 is true and return 1]
1

Q. Write down the order of the precedence of all the C++ operators.

Ans: The order of the precedence (from top to bottom) in decreasing order of all the C++ operators are
as follows:

Operator symbol Operator name

:: Scope resolution operator


() Function call
[] Array access
-> Member access from a pointer
. Member access from an object
++ Post-increment
-- Post-decrement
! Logical negation
~ Bitwise complement
++ Pre-increment
-- Pre-decrement
- Unary minus
+ Unary plus
* Dereference
& Address of
(type) Cast to a given type

9
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

sizeof Return size of an object


->* Member pointer selector
.* Member object selector
* Multiplication
/ Division
% Modulus
+ Addition
- Subtraction
<< Bitwise shift left
>> Bitwise shift right
< Comparison less-than
<= Comparison less-than-or-equal-to
> Comparison greater-than
>= Comparison greater-than-or-equal-to
== Comparison equal-to
!= Comparison not-equal-to
& Bitwise AND
^ Bitwise exclusive OR (XOR)
| Bitwise inclusive (normal) OR
&& Logical AND
|| Logical OR
?: Ternary conditional (if-then-else)
= Equals

Q. Find the values of x >> 2 and x & y using the following declaration:
unsigned char x = ‘\011’, y = ‘\027’;
Ans:

The output will be as follows :


x>>2 : The character corresponding to the ascii value of 2
Explanation :
The value ‘\011’ is basically a non-printable character  horizontal tab
Howe’er, Octal value of x will be 9 or 1001 so, applying right shift by 2 we have 0010 2.
Its ascii equivalent is printed.
x&y : The character corresponding to the ascii value 1
Explanation :
The value ‘\027’ and ‘\011’ both are true/non-zero values, hence x&y gives true i.e. 1. Its
ascii is printed.

Q. Determine the value of min :


int m = 1, n = 2;
int min = (m < n ? m-- : n++);
Ans:

The value of min will be 1.


Explanation :
Here the condition (m<n) in the ternary operator is true, so min will take the value from the first
part of the operator. But here m is getting the post decrement, so the value of m will be assigned to
min first and then decremented.

Q. What is the size of float in C++?


Ans:
In C++, we can define the size of float in two ways.
1) The size of memory space, it takes to store a floating value. Then the size is of 4 bytes.
2) The number of digits in to a floating variable. And that is 38 before the decimal point and
maximum of 6 digits after the decimal point.

10
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Howe’er, the size of a data type can be OS specific also.

Q. Differentiate between keyword and identifier.


Ans:
Keyword Identifier
1. Keywords implement specific C++ 1. Identifiers denote the features of the
language features. They are explicitly variables used in a program.
reserved identifiers.
2. Keywords cannot be used as names for 2. Identifiers refer to the names of
the program variables or other user- variables, functions, arrays, classes,
defined program elements. etc. created by the programmer.
3. Keywords are built-in names of C++ 3. Identifiers are user-defined names
that are used in program. maintaining some rules that are used
in program. The keywords may have
identifiers along with them.
4. Example: class, default, friend, public. 4. Example: string name, int code.

Q. Are the identifiers ‘name’ and ‘NAME’ different in C++? Explain.


Ans:
Yes, the identifiers ‘name’ and ‘NAME’ are different in C++. Because when the identifiers are
declared in C++, then they are case sensitive. Here the identifier ‘name’ is in lower case and the
identifier ‘NAME’ is in upper case and they are treated as different.

--------------------------------------
Long Answer Questions
--------------------------------------

Q. What do you mean by C++ pre-compiler directives, built-in functions and various tokens?
Ans:

The C++ preprocessor or C++ pre-compiler (cpp) is the preprocessor for the C++ programming
language. In many C++ implementations, it is a separate program invoked by the compiler as the
first part of translation. The preprocessor handles directives for source file inclusion (#include),
macro definitions (#define), and conditional inclusion (#if). The language of preprocessor directives
is not strictly specific to the grammar of C++, so the C++ preprocessor can also be used
independently to process other types of files.

Examples of Pre-compiler

 #define  #error  #include


 #elif  #if  #line
 #else  #ifdef  #pragma
 #endif  #ifndef  #undef

A built-in function is a function that is supplied with C++ compiler. A built-in function is denoted
by a function name followed by zero or more operands which are enclosed in parentheses. The
operands of functions are called arguments, and each argument is specified by an expression. The
result of a function is a single value derived by applying the operation of the function to the
arguments.

Examples: All the built in C functions are example of C++ functions. E.g., puts(char *) is a built in
function to show a complete string.

11
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Smallest individual units in a program are known as tokens.


C++ has the following tokens :

 Keywords
 Identifiers
 Constants
 Strings
 Operators

Q. Differentiate between the following: Logical and bitwise operator, Increment and decrement
operators, Simple assignment and short hand assignment operator.
Ans:

Logical operator Bitwise operator


1. The logical operator evaluates the 1. The Bitwise operator evaluates the expression to
expression and produces result on the basis produce result in binary values.
of ‘true’ or ‘false’.
2. Some logical operators are && (and), || 2. Some bitwise operators are & (AND), | (OR),
(or). ^ (XOR), ~ (Inversion).
3. For example, a > 6 && y < 20. It will 3. For example, a ^ b will produce a result 0 if both
produce result ‘true’ if both a>6 and y<20 is the bits are of the same value and 1 if the bits have
true, otherwise the result is false. different values.

Increment operator Decrement operator


1. The increment operator increases the value 1. The decrement operator decreases the value of
of the variable attached to the operator. the variable attached to the operator.
2. The increment operator is ‘++’. 2. The decrement operator is ‘--’.
3. The expression ++i adds 1 to i, and stores 3. The expression --i subtracts 1 from i, and stores
the incremented result back in i. the decremented result back in i.
4. There is an unary increment operator, 4. There is an unary decrement operator, denoted
denoted by ‘+’. by ‘-’.

Simple assignment operator Shorthand operator


1. The Simple Assignment operator is basically 1. The Shorthand operator is a combination of two
a single assignment operator in process. operators in process.
2. Example of simple assignment operator is 2. The simple assignment operator is ‘+=’.
‘+’.
3. For example, to add the value of a and b and 3. For example, to add the value of a and b and
store the added value to a, it is written as a = a store the added value into a, it is written as a += b;
+ b;. So, it can be expressed using two though the task is two in number, it can be done by
operators. using a single shorthand operator.
1. Its simple. i.e. value of right hand side 4. Here, the limitation is that the variable on the left
operand is assigned to left hand side operand. side operand is involved in the evaluation of the
expression & the assignment operation as well. We
cannot restrict it to individual operation in isolation.

Q. What do you mean by jump statements? What are the different jump statements in C++?
Ans:
Jump statements can be used to modify the behavior of conditional and iterative statements. Jump
statements allow to exit a loop, start the next iteration of a loop, or explicitly transfer program

12
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

control to a specified location in the program. So, they are also known as the breaking control
statements.

In C++, there are various jump statements as given below:

1) Break Statement: The break statement causes the program flow to exit the body of the while
loop.

For example:

int main()
{
-----
-----

if (num2 = = 45)
break;
}

The condition exits the loop when the condition, num2 == 45, becomes true.

2) The continue Statement : The continue statement, like break statement, skips over a part of the
code. But, unlike break statement, it forces the next iteration of the loop to take place, skipping any
code in between.
For the ‘for’ loop, ‘continue’ causes the next iteration by updating the variable and then
causing the test-expression’s evaluation. For the ‘while’ and ‘do-while’ loops, the program control
passes to the conditional test.
It is used in the program as follows:

while (expression)
{
statement 1;
if (condition)
continue;
statement 2;
}
while(expression);
statement 3;

3) The goto Statement : A goto statement can transfer the program control anywhere in the
program. The target destination of a goto statement is marked by a label. The target label and goto
must appear in the same function.
The syntax of goto statement is:

goto label;
----
----
label: ;

where label is a user supplied identifier and can appear before or after goto.

4) The return Statement : A ‘return statement’ ends the processing of the current function and
returns control to the caller of the function.
A value-returning function should include a return statement, containing an expression.
If an expression is not given on a return statement in a function declared with a non-void return

13
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

type, the compiler issues a warning message. If an expression is not given on a return statement
in a function declared with a non-void return type, the compiler issues an error message.
If the data type of the expression is different from the function return type, conversion of
the return value takes place as if the value of the expression were assigned to an object with the
same function return type.
For a function of return type void, a return statement is not strictly necessary. If the end of
such a function is reached without encountering a return statement, control is passed to the caller as
if a return statement without an expression were encountered. In other words, an implicit return
takes place upon completion of the final statement, and control automatically returns to the calling
function.

The following are examples of return statements:

return; /* Returns no value */


return result; /* Returns the value of result */
return 1; /* Returns the value 1 */
return (x * x); /* Returns the value of x*x */

Q. What is Command Line Argument?


Ans:
The main function may be defined not to have any parameter. In some cases, the program is
provided with some input values at the time of execution. These values are known as command
line arguments or parameters. If the ‘main’ function must process the command line parameters,
it should be defined as having two parameters – ‘argc’ of ‘int’ type and ‘argv’ of pointer to
character type array.

‘argc’ is initialized with a number of parameters provided in command line while ‘argv’ points to
the list of parameters itself, as shown below:

#include<iostream.h>
void main (int argc, char *argv[])
{
for (int i=1; i<argc; i++)
cout<<‘\n’<< argv[i];
}

Let us suppose that the name of the program is ‘abc.exe’. Executing this program from the
command line as below:
C:\> abc delhi agra kolkata

will produce the below output:

C:\> abc
delhi
agra
kolkata

Here, the parameter ‘argc’ is initialized with the number of command line arguments plus one.
These command lines are stored in argv[1], argv[2],…. The name of the program is itself stored in
argv[0].

The command line arguments are always read as string of characters even if a numeric value is
passed as argument. The name of the arguments can be any valid name as long as the type are ‘int’
and ‘char *’ respectively, as shown below:

14
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

#include<iostream.h>
void main(int a, char *ar[])
{
for (int i = 0; i<a; i++)
cout <<‘\n’<< ar[i];
}

Q. What is pointer arithmetic? How is it performed? Support your answer with an example.
Ans:
Pointer arithmetic refers to the application of some of the arithmetic operators to pointers. The
pointer arithmetic is different from ordinary arithmetic in the sense that pointers must conform to
special constraints in order to make them behave properly. For example, a common operator to use
with pointers is ++, which “adds one to the pointer.” This implies that the pointer is changed to
move to “the next value”.

While calculating the result of a pointer arithmetic expression, the compiler always multiplies the
integer operand by the size of the object being pointed to. This is called scaling.

The following program shows an example of pointer arithmetic :

int nValue = 7;
int *pnPtr = &nValue;

cout<< pnPtr<<endl;
cout<< pnPtr+1<<endl;
cout<< pnPtr+2<<endl;
cout<< pnPtr+3<<endl;

Output is :

0012FF7C
0012FF80
0012FF84
0012FF88

In the above example, each of the addresses differs by 4 (7C + 4 = 80 in hexadecimal). This is
because an integer is 4 bytes on the machine at the time of developing the above program.

Q. What are the various data types available in C++?


Ans:

When programming, we store the variables in our computer's memory, but the computer has to
know what kind of data we want to store in them, since it is not going to occupy the same amount of
memory to store a simple number than to store a single letter or a large number, and they are not
going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory that
we can manage in C++. A byte can store a relatively small amount of data: one single character or a
small integer (generally an integer between 0 and 255). In addition, the computer can manipulate
more complex data types that come from grouping several bytes, such as long numbers or non-
integer numbers.
Next you have a summary of the basic fundamental data types in C++, as well as the range of values
that can be represented with each one :

Name Description Size* Range*

15
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

signed: -128 to 127


char Character or small integer. 1byte
unsigned: 0 to 255
short int signed: -32768 to 32767
Short Integer. 2bytes
(short) unsigned: 0 to 65535
signed: -2147483648 to
int Integer. 4bytes 2147483647
unsigned: 0 to 4294967295
signed: -2147483648 to
long int
Long integer. 4bytes 2147483647
(long)
unsigned: 0 to 4294967295
Boolean value. It can take one of two
bool 1byte true or false
values: true or false.
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
Double precision floating point +/- 1.7e +/- 308 (~15
double number.
8bytes
digits)
Long double precision floating point +/- 1.7e +/- 308 (~15
long double number.
8bytes
digits)
wchar_t Wide character. 2 or 4 bytes 1 wide character

The values of the columns Size and Range depend on the system the program is compiled for. The
values shown above are those found on most 32-bit systems. But for other systems, the general
specification is that int has the natural size suggested by the system architecture (one "word") and
the four integer types char, short, int and long must each one be at least as large as the one
preceding it, with char being always 1 byte in size. The same applies to the floating point types
float, double and long double, where each one must provide at least as much precision as
the preceding one.

Q. What is a pointer variable? How are pointers important in a programming language? Give an
example of use of pointers in C++?
Ans:
A pointer variable is a special variable that return the address of a memory. The only difference
between a pointer variable and a regular variable is that a regular variable can contain values,
whereas a pointer variable does not contain values, but the address of a value. A pointer follows all
the usual naming rules of regular, non-pointer variables.

In a programming language, whenever we declare a variable, the system allocates, somewhere in


the memory, a memory location and a unique address is assigned to this location. Hence, a pointer
is very useful in order to hold the address of a memory location rather than the value of the location.
As the memory addresses are numbers, they can be assigned to some other variable.

Let us take an example of storing a value of 20 in a variable named ‘age’. Here, C++ store the value
of 20 after reserving storage for the variable age. Now, suppose that it is required to declare a
pointer variable, not to hold the age, but to point to the variable age.

The following program example demonstrates the declaration and use of pointer in C++:

#include<iostream.h>
int main( )
{
int i = 20, *p_age;
p_age = &i;
cout<<i<< “ “<<*p_age<<endl;
}

16
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

In the above program, p_age is a pointer variable that hold the address of the integer variable i.

Q. What is parameter passing? Explain with example call by reference scheme in C++.
Ans:
Parameter passing methods are the ways in which parameters are transferred between functions
when one function calls another. C++ provides two parameter passing methods—‘pass-by-
value’ and ‘pass-by-reference’.

A reference is an alias name for a variable. In C++, the call by reference method is useful in cases
where the values of the original variables are to be changed using a function.

An example of invoking a function call by reference

Let us take an example program to swap values of two variables using pass by reference method.

#include<iostream.h>
#include<conio.h> //for clrscr

int main()
{
clrscr();
void swap (int &, int &); //prototype
int a = 7, b = 4;
cout << “Original values \n”;
cout << “a = ” << a << “b = ” << b << “\n”;

swap(a, b); //invoke the function


cout << “swapped values \n”;
cout << “a = ” << a << “b = ” << b << “\n”;
return 0;
}

void swap (int &x, int &y) //function body


{
int temp;
temp = x;
x = y;
y = temp;
}

The output produced by the above program is as follows:

Original Values
a = 7, b = 4

Swapped Values
a = 4, b = 7

In the above program, the function swap() creates reference ‘x’ for the first incoming integers and
reference ‘y’ for the second incoming integer. Thus the original values are worked with but by using
the names x and y. The function call is simple as shown below:
swap (a, b);

But the function declaration and definition include the reference symbol ‘&’. The function
declaration and definition, both, start as
void swap(int &, int &)

17
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Therefore, by passing the references the function works with the original values (i.e., the same
memory area in which original values are stored) but it uses alias names to refer to them. Thus, the
values are not duplicated.

Q. Differentiate between the followings: pre and post increment/decrement operators, unary plus and
unary minus operator, comparison and equality operators.

Ans:
(i) pre and post increment operator

The Pre-increment operator increments the object and returns the current object value after
incrementation;
Whereas, the Post-increment operator increments the value of the object but returns the value of the
object before it was incremented. As the object has now been incremented this means the before
increment value must be saved before the increment occurs and this copy returned after the
increment has occurred.

The Pre-increment operator puts the name of the variable after the increment operator, viz., ++i;
Whereas, the Post-increment operator puts the name of the variable before the increment operator,
viz., i++;

For example if n has the value 5 then,


i = n++;
would set i to the original value of n i.e. 5 and would then increment n to 6.
Whereas,
i = ++n;
would increment n to 6 and then set i to 6.

(ii) pre and post decrement operator

The Pre-decrement operator decreases the object and returns the current object value after
decrementation;
Whereas, the Post-decrement operator decreases the value of the object but returns the value of the
object before it was decremented. As the object has now been decremented this means the before
decrement value must be saved before the decrement occurs and this copy returned after the
decrement has occurred.

The Pre-decrement operator puts the name of the variable after the decrement operator, viz., --i ;
Whereas, the Post-decrement operator puts the name of the variable before the decrement operator,
viz.,
i-- ;

For example if n has the value 5 then,


i = n--;
would set i to the original value of n i.e., 5 and would then decrement n to 4.

Whereas,
i = --n;
would decrement n to 4 and then set i to 4.

(iii) unary plus and unary minus operator

The unary plus operator returns the value itself of the operand. For example, if x = -5, +x gives +(-
5) = -5.
The unary minus operator returns the operand multiplied by -1. For example, if x = 5, -x gives -5.

18
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

However,
In the C family of languages, the following operators are unary :

 Increment  ++x, x++


 Decrement  − −x, x− −
 Address of  &x
 Indirection(value at…)  *x
 Positive  +x
 Negative  −x
 One's complement  ~x
 Logical negation  !x
 Sizeof  sizeof(x) / sizeof(type-name)
 Cast  (type-name) cast-expression

(iv) comparison and equality operator

The comparison operator compares the value of the left side and the value of the right side. If both
the values are equal then it returns the truth value 1.
The equality operator assigns the value of the right to the variable of the left side.

Q. Why comments, symbolic statements and special operators are used in C++ programming?
Ans:
Comments in a program are used to document the statements that programmers write. It is
recommended to provide a comment to every program in order to explain the objective of the
program.
Comments are represented with double slash (//) for a single line. But, if the comment involves
more than one line, then it is represented putting /* before the first word of the comment that begins
the comment section and */ after the last word of the comment that ends the comment section.

Symbolic statements are used to minimize the length of the regular statements and blocks.
C++ has some extra ordinary concept over Object Oriented Programming. To give the symbolic
form of those operations, C++ uses some special operators.

Special Operators are the operators used instead of some referencing operators in order to make the coding
much easier and simple. For instance, for a pointer variable p, it would be very time- consuming to
write (*p).num every time, specially when there are a lot of classes [Suppose writing
(*(*(*(*MyPointer).Member).SubMember).Value) is highly confusing and tedious]. As a result, a
special operator, ->, exists. Instead of (*p).num, we can write p->num, which is completely identical for
all purposes. Now that large referencing code will become MyPointer- >Member->SubMember->Value
which is quite easy.

Q. What are the different operators in C++? What are the differences between associativity and
hierarchy of operators

Ans: In C++, the different types of operators are as given below:

 Arithmetic operators
 Assignment operators
 Unary operators
 Comparison operators

19
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

 Shift operators
 Bit-wise operators
 Logical operators
 Conditional operators

Associativity Hierarchy
Operators associate with either the expression on Operators follow a strict order, which
their left or the expression on their right; this is defines the evaluation order of expressions
called "associatively” containing these operators; this is called
Hierarchy or precedence.
Associatively is of two types. The Hierarchy or precedence of each and
i)Left to Right. every operator is unique.
ii)Right to Left
Example: Example:
The comma operator has an associatively Left to The comma operator is in the lowest
Right. position of the operator hierarchy.

TOPIC : CONTROL STATEMENTS & LOOPING


--------------------------------------
Short Answer Questions
--------------------------------------

Q. What is a nested loop?


Ans:
A ‘nested loop’ is a loop within a loop, an inner loop within the body of an outer one. The first pass
of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the
outer loop triggers the inner loop again with the second iteration value of the first loop. These
operations continues in the same way until the outer loop finishes. However, a ‘break’ within either
the inner or outer loop can interrupt the continuous process of the loop.
For example :
for(int i = 0; i<10 ; i++)
{
for( j = 0; j<10; j++)
{ /*statements here…*/ }
}

Q What does this for (; ;); statement do?


Ans:
This is a false loop. A false loop has no statement with in it. The loop for( ; ; ); will execute the
control, but dose not execute any statement.
Secondly, this loop has no initialization, condition and increment or decrement. So, compiler will
treat it as an infinite loop and the loop will execute infinite number of times. All the statement after
this loop will not be executed.

Q. Give an example of “continue” control statement in C++.


Ans:
The example of “continue” control statement in C++ is as follows:

#include <iostream.h>

int main ()
{

20
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

int x;

x = 0;
while (x < 10)
{
++x;
if (x % 2 = = 0)
continue;
cout<<x<<" is an odd number."<< endl;
}
}

The output of the above program is :

1 is an odd number.
3 is an odd number.
5 is an odd number.
7 is an odd number.
9 is an odd number.

Here all the even numbers will be skipped.

Q. What is break statement?


Ans:
A break statement lets you end an iterative (do, for, or while) statement or a switch statement and
exit from it at any point other than the logical end. A break may only appear on one of these
statements.
A break statement has the form:

>>break--;----------------------------------------------------><

In an iterative statement, the break statement ends the loop and moves control to the next statement
outside the loop. Within nested statements, the break statement ends only the smallest enclosing
do, for, switch, or while statement.
In a switch statement, the break passes control out of the switch body to the next statement outside
the switch statement.

Example :
switch(ch)
{
case 1:
//----------------
//Do something
//----------------
break ;
}

Q. When will you use break statement?


Ans:
The ‘break’ statement is used to break out from a block(generally enclosed by a pair of braces) of
code. In general, we use a 'break' statement within a loop where on raise of certain condition the
control will be out of the loop.
e.g.
...
for(x = 0; x<=100; x+=3)

21
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

if(x%11 = = 0)
break;
else printf(“%d”,x);
...
Here the loop will be discontinued if a number divisible by 11 is found, else printing each third
values from 0 to 100.

'break' statement is used with the conditional ‘switch’ statement and with the ‘do’, ‘for’, and ‘while’
loop statements.
The 'break' statement is typically used to handle the cases in a 'switch' statement where we usually
may want the program to ignore invalid cases. In a 'switch' statement, 'break' causes the program to
execute the next statement after the 'switch'. Without a 'break' statement every statement from the
matched case label to the end of the 'switch', including the default, is executed which is known as
fall through error (logical).
In a 'for' statement, the 'break' can stop the counting when a particular condition becomes true. For
example, the following program is supposed to count from 0 to 12, but the programmer wants it to
stop as soon as it detects the number 5.

Q. Give an example of “goto” control statement in C++.


Ans:
The example of “goto” control statement in C++ is as follows:

#include<iostream.h>
int main()
{
int a =0;
start:
cout<<“\n”<< ++a;
if (a<50)
goto start;
}

The above program will print numbers from 1 to 50.

Q. Write a for loop in C++ to print even number from 1 to 20.


Ans:

for(int i=1; i<=20; i++)


{
if(i%2= =0)
{
cout<<i<<endl;
}
}

--------------------------------------
Long Answer Questions
--------------------------------------

Q. What is the role of various Switch statements in the C++ programming?


Ans:
C++ provides a multiple-branch selection statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants. If a
match is found, the statements associated with that constant are executed.

22
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

The syntax is :

switch (expression)
{
case constant1: statement sequence 1;
break;
case constant2: statement sequence 2;
break;
case constant1: statement sequence n-1;
break;
----------
----------
[default: Statement sequence n];
}

The expression is evaluated and its values are matched against the values of the constants specified
in the case statements. When a match is found, the statement sequence associated with that case is
executed until the break statement or the end of switch statement is reached. The default statement,
if any provided, gets executed when no match is found. If there is not default statement, nothing
will happen on getting no match.
When a break statement is encountered in a switch statement, program execution jumps to
the line of code following the switch statement i.e., outside the body of switch statement. Thus,
break statement is one of the jump statements of C++.

Let us see the below program containing the switch and break statements.

#include <iostream.h>
int main()
{
int dow;
cout << “Enter number of day in a week (1-7) : ”;
cin >> dow;
switch(dow)
{
case 1: cout << “\n” << “Sunday”;
break;
case 2: cout << “\n” << “Monday”;
break;
case 3: cout << “\n” << “Tuesday”;
break;
case 4: cout << “\n” << “Wednesday”;
break;
case 5: cout << “\n” << “Thursday”;
break;
case 6: cout << “\n” << “Friday”;
break;
case 7: cout << “\n” << “Saturday”;
break;
default: cout << “\n” << “wrong number of day”;
}
return 0;
}

The above program will take input for the number of days in a week (1 – 7) and translate it to its
equivalent name.

23
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Discuss the various IF statements. Why the ladder IF statement is used?


Ans:
The IF statement is a type of conditional statement of C++. An IF statement tests a particular
statement; if the given condition evaluates to true, a set of defined actions will execute; otherwise
the set of actions will be ignored.
The syntax for using the if statement is:
if(expression) <statement>;

where <statement> may be empty or consist of a single or compound statement. The expression
must be enclosed in parenthesis. If the expression evaluates to true i.e., a non-zero value, the
statement is executed, otherwise ignored.

E.g.:
int A, B, C;
cin>>A>>B;
if (A>10 && B<15)
{
c = (A – B)*(A + B);
cout<<“The result is “<<C<< “\n”;
}

Another type of ‘if statement’ is the “if-else statement”. Here, the ‘if’ conditional construct is
followed by a logical expression in which data is compared and a decision is made based on the
result of the comparison.
The syntax is:
If (boolean_expr)
{
//statements;
}
else
{
//statements;
}

The ‘if-else’ statement is used to carry out a logical test and then take on of two possible actions,
depending on the result of the condition (true or false).

For example :

#include<iostream.h>
int main()
{
char chr;
cout << “please enter a character: ”;
cin >> chr;
if(chr == ‘X’)
cout << endl << “The character is X”;
else
cout << endl << “The character is not X”;
return 0;
}

In the above program, if we provide ‘X’ as input, it will display ‘The character is X’, else, it will
display ‘The character is not X’.

24
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

The ladder if statement is used in a case where the result depends on the happening of multiple
conditions. In this case, as soon as a true condition is found, the statement associated with it is
executed and the rest of the ladder is bypassed. If none of the conditions are true, the final else is
executed. That is if all other conditional tests fail the last else statement is performed.

The following program uses the ladder if….else statement to evaluate whether the entered character
is uppercase or lowercase.

#include <iostream.h>
int main()
{
char inp;
cout << “Please enter a character: “;
cin >> inp;
if(inp >= ‘A’)
if (inp <= ‘Z’)
cout << endl << “Uppercase”;
elseif (inp >= ‘a’)
{
if (inp <= ‘z’)
cout << endl << “Lowercase”;
else
cout << endl << “Input character > z”;
}
else
{
cout << endl << “input characters > z but less than a”;
}
else
{
cout << endl << “Input character less than A”;
}
return 0;
}

Q. What are the various loop control statements in C++? Explain briefly.
Ans:

Loops are basically means to do a task multiple times, without actually coding all statements over
and over again.

For example, loops can be used for displaying a string many times, for counting numbers and of
course for displaying menus.

Loops in C++ are mainly of three types :

1. 'while' loop
2. 'do while' loop
3. 'for' loop

The 'while' loop :-


CODE

#include<iostream.h>

25
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void main()
{
 int i=0;
 while(i<3)
 {
   i++;
   cout<<"ABC"<<endl;
 }
}

The output of the above code will be :


ABC
ABC
ABC

The 'do while' loop :


It is very similar to the 'while' loop shown above. The only difference being, in a 'while' loop, the
condition is checked beforehand, but in a 'do while' loop, the condition is checked after one
execution of the loop.

Example code for the same problem using a 'do while' loop would be :

CODE

void main()
{
 int i=0;
 do
 {
   i++;
   cout<<"ABC"<<endl;
 }while(i<3);
}

The output would once again be same as in the above example.

The 'for' loop :-


This is probably the most useful and the most used loop in C/C++. The syntax is slightly more
complicated than that of 'while' or the 'do while' loop.

The general syntax can be defined as :


for(<initial value>;<condition>;<increment/decrement>)

The code for this would be :

CODE

#include<iostream.h>

26
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void main()
{
 for(inti=1;i<=5;i++)
  cout<<i<<endl;
}

The output for this code would be :-


1
2
3
4
5
Here variable 'i' is given an initial value of 1. The condition applied is till 'i' is less than or equal to
5. And for each iteration, the value of 'i' is also incremented by 1.

Q. Justify why the for loop is most popular among programmers.


Ans:
The “for loop” is popular among programmers than any other type of loop. This is because, the for
loop works very fine with defined values. It includes an expression that specifies an initial value for
an index, another expression that determines whether or not the loop is continued, and a third
expression that allows the index to be modified at the end of each pass.
The general form of the for loop is:
for (expression-1; expression-2; expression-3)
loop statements;

When the ‘for’ statement is executed, expression-1 is executed once only at the start of the first
pass, expression-2 is evaluated and its truth is tested at the beginning of each pass through the loop,
and expression-3 is evaluated at the end of each pass.

The ‘for’ loop allows many variations like we can skip the expression-1 i.e. initialization part or the
condition part i.e. expression-2 or the increment/decrement part i.e. expression-3 or any two or
even all. Therefore the structure of the loop is very much flexible. E.g.
for(; i<5; i++)
for(i = 0; ; i++)
for(i = 0; i<5; )
for(; ; ); //infinite loop

Howe’er, in order to satisfy the loop’s operation the logic should be placed somewhere else at
programmer’s liberty.

Here, the conditional test is always performed at the top of the loop, so that the set of statements
defined within it should not execute until the given condition is true. These features make it
popular, as with the other loop like ‘Do While’, the condition is checked after the set of commands
within it works once and might produce erroneous result if the condition is not met.

Thus, for loop is highly useful for programmers.

Q. Compare between the conditional control statement and null statement.


Ans:

The null statement has no sets of instructions for its execution. That means any instruction will
never be executed under any circumstances within the null statement, because, the null statement
has no instruction with in it.

27
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

For example : A false loop.


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

This loop increments 'i' using the ++ operator 10 times. When the statement is executed, the null
statement evaluates to nothing, and consequently, doesn’t do anything. For readability purpose, the
semicolon of a null statement is typically placed on it’s own line. This indicates that the use of a
null statement was intentional, and makes it harder to overlook the use of the null statement.
Alternatively,
A null statement can be used when a label is needed before the end of a block statement.
For example:

void func(void)
{
if (error_detected)
goto depart;
/* further processing */
depart:; /* null statement required here */
}

But, the conditional statement has instructions with in it and the instructions are condition
dependent. i.e., if the conditions are true, then the conditional statement will execute the instructions
with in it and if the conditions are false, then the instructions will not be executed.
The conditional control statement allows to choose the set-of-instructions for execution depending
upon an expression, truth value.

Example : if and else block.

if(condition)
{
Statements 1;
}
else
{
Statements 2;
}

Null statements can actually be used anywhere a regular statement can be(though they typically
aren’t, since they serve no purpose other than as a do-nothing placeholder). Because of this, it is
easy to make the following mistake :

if (nValue = = 0);
nValue = 1;

The programmer’s intent was to assign nValue the value of 1 only if nValue had the value 0.
However, due to the misplaced semicolon after the if statement, this actually executes as:

if (nValue == 0)
;
nValue = 1;
Consequently, nValue is set to 1 regardless of it’s previous value!

28
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

TOPIC : CLASSES and OBJECTS , CONSTRUCTOR

--------------------------------------
Short Answer Questions
--------------------------------------

Q. Bring out the differences between classes and structures in C++.


Ans:

In C++, the differences between the classes and the structures are as follows :

Class Structure
1. A class is a concept of C++ that emerges from 1. A structure (or struct) is a derived/user-
structure concept. defined data type originated from C.
2. Class members can be encapsulated to 2. Structure members do not have this facility.
facilitate different selective access mode of
them.
3. By default, inheritance of class is private. 3. By default, inheritance of structure is public.
4. A class contains attributes & behaviours of a 4. A structure contains only the attributes of an
real-life entity. entity, but not the behaviour.
5. A class exhibits the data abstraction property. 5. A structure does not do so.

Q. Explain with example about constructor overloading in C++.


Ans:

class test
{
int i, j;
public:
int cal()
{
return(i + j);
}
test(int a)
{
i = a;
j = 0;
}
test(int a, int b)
{
i = a;
j = b;
}
}

Here the constructor, test() of the class test is overloaded. The first one is taking only one argument
and the second one is taking two arguments. So, here the calling on the constructors is depending on
the number of arguments of the constructor.

Q. Differentiate between class and object.


Ans:
Class Object

29
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

1. A class is an encapsulation of objects, 1. An object is an instance of a class.


data & functions.
2. A class is static. All of the attributes of a 2. An Object on the other hand has a
class are fixed before, during, and after the limited lifespan. Objects are created and
execution of a program. eventually destroyed.
3. The attributes of a class don't change. 3. The attributes of the object may undergo
significant change.
4. For example, ‘car’ is a class that contains 4. For example, in a class ‘car’, the
attributes, like, colour, shape, etc. creation date is an object.

Q. What’s the order that local objects are destructed?


Ans:
On exit from a scope, destructors are called for all local automatic objects that are declared in that
scope, in the reverse order of their declaration.
For example :

void f()
{
CmyClass obj1; // 1
CmyClass obj2; // 2
}

obj1 is constructed before obj2. On exit from f(), the objects are destroyed in the reverse order of
their declaration or construction, so obj2 will be destroyed before obj1.

Q. When is a destructor not called automatically?


Ans:
When an exception is thrown for a class object with a destructor, the destructor for the temporary
object thrown is not called until control passes out of the catch block.

Q. What is the primary purpose of a default constructor in C++?


Ans:
A default constructor is a constructor that either has no parameters, or if it has parameters, all the
parameters have default values. The primary purpose of a default constructor is to initialize the data
variables of the object to valid initial values. The default constructor method is called automatically
at the time of creation of an object.
If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares
a default parameter less constructor A::A(). This constructor is an inline public member of its
class. The compiler will implicitly define A::A() when the compiler uses this constructor to create
an object of type A. The constructor will have no constructor initializer and a null body.
The compiler first implicitly defines the implicitly declared constructors of the base classes and
non-static data members of a class A before defining the implicitly declared constructor of A. No
default constructor is created for a class that has any constant or reference type members.

Q. What is a copy constructor in C++?


Ans:
A copy constructor method allows an object to be initialized with another object of the same class.
It implies that the values stored in data members of an existing object can be copied into the data
variables of the object being constructed, provided the objects belong to the same class. A copy
constructor has a single parameter of reference type that refers to the class itself as shown below:

abc : : abc(abc & a)

30
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

{
x = a.x ;
y = a.y ;
}
Suppose we create an object ‘myabc1’ with two integer parameters as shown below:

abc myabc1(1, 2);

Now, another object can be created of abc type from ‘myabc1’, as shown below:

myabc2 = abc (& myabc1);

The data values of ‘myabc1’ will be copied into the corresponding data variables of object
‘myabc2’. Another way of activating copy constructor is through assignment operator. Copy
constructors are used when an object is assigned another object of the same type, as shown below:

abc myabc1(1, 2);


abc myabc2;
myabc2 = myabc1;

Here, the assignment operator (=) has been overloaded so that the copy constructor is invoked
whenever an object is assigned another object of the same type.

Q. What is the role of a constructor?


Ans:
A ‘constructor’ is a member function with the same name as its class.
For example:
class X
{
public :
X(); // constructor for class X
};

Constructors are used to create, and can initialize, objects of their class type. A constructor can
neither be declared as virtual or static, nor as a constructor as const, volatile, or
const volatile. A constructor doesn’t involve any return type. A return statement in the body
of a constructor cannot have a return value.
A constructor can also be defined as a function that initializes the members of an object. A
constructor only knows how to build an object of its own class. A function to which the
constructor function attribute has been applied is called automatically before execution enters
main.
Constructors are not automatically inherited between base and derived classes. If we don't make one
constructor in the derived class, a default will be provided by the compiler without any parameters,
but this will not execute in the desired way.
There must always be a constructor, even if it is the default and empty. If we supply a constructor
with parameters then a default will NOT be created.

Below given are some notable points about constructors:


 Constructors are just functions with the same name as the class.
 Constructors are intended to initialize the members of the class when an instance of that class is
created.
 Constructors are not called directly (except through initializer lists)
 Constructors are never virtual.
 Multiple constructors for the same class can be defined. They must have different parameters to
distinguish them.

31
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. What do you mean by classes in classes?


Ans:
A class is basically a structure containing data members and functions that manipulate the data. A
class that is declared within the scope of another class is known as nested class.

A nested class is declared within the scope of another class. The name of a nested class is local to its
enclosing class. Unless we use explicit pointers, references, or object names, declarations in a
nested class can only use visible constructs, including type names, static members, and enumerators
from the enclosing class and global variables.

Member functions of a nested class follow regular access rules and have no special access privileges
to members of their enclosing classes. Member functions of the enclosing class have no special
access to members of a nested class.

Example of a nested class as follows :


class outside
{
public:
class nested
{
public:
static int x;
int g();
};
};

18. Write short note on Container class.


Ans:
Container classes are used to maintain collections of elements like stacks, queues, linked lists,
tables, trees, etc. Container classes form the basis for various C++ class libraries.

The objectives of Container Class are as follows:

Application Independence - Transparently reuse container class code for various applications.

Ease of Modification - Relatively easy to extend classes to fit smoothly into a new application.

Ease of Manipulation - Implementation must hide representation details, e.g., iterators.

Type Safety - Insure that the collections remain type safe. This is easy for parameterized types,
harder
for void pointers.

Run-Time Efficiency and Space Utilization - Different schemes have different tradeoffs; e.g., extra
indirection vs flexibility.

A Container can also be defined as a data structure that holds a number of objects of the same type
or class. The most common example of a Container in C++ is an array as shown below:

const int MAX = 10;


float a[MAX];
...
for(int i=0; i<10; ++i)
process(a[i]);

32
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

...

Lists, Queues, Vectors, etc. are all containers.

--------------------------------------
Long Answer Questions
--------------------------------------

Q. How does C++ support dynamic memory allocation?


Ans:
Let us consider a case of a program in C++ where it is required to store a particular number
(specified by the user at runtime) of phone numbers. Here, declaring array of 10 or 20 elements will
be of no use as we don’t know exactly how many numbers the users will enter. They may want to
enter 1, 10 or even 100 phone numbers.
Hence, the only choice is to use the ‘Dynamic Memory Allocation’ of C++ programming
language to allocate only the needed amount of memory.

Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as below:

ptr = new DataType(initializer);

Here, ptr is a valid pointer of type DataType, which is also a valid C++ data type.
Initializer (optional) if given, the newly allocated variable is initialized to that value.

//Example Program in C++


#include<iostream.h>

void main(void)
{
int *ptr;
ptr = new int(10);
cout<<*ptr;
delete ptr;
}

This will allocate memory for an integer having initial value 10, pointed by the ‘ptr’ pointer.

Memory space for arrays (i.e., a set of values) is allocated as shown below:

ptr = new DataType[x];

Here, x is the number of elements and C is a constant.

//Example Program in C++


#include<iostream.h>

void main(void)
{
int *ptr, size;

cin>>size;
ptr = new int[size];

//arrays are freed-up like this

33
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

delete []ptr;
}

Q. What is object oriented programming? How does an object oriented program differ from a
structured program?
Ans:
The term object-oriented programming (OOP) is widely used. Object oriented programming is a
type of programming in which programmers define not only the data type of a data structure, but
also the types of operations (functions) that can be applied to the data structure. In this way, the data
structure becomes an ‘object’ that includes both data and functions. In addition, programmers can
create relationships between one object and another, e.g., objects can inherit characteristics from
other objects.

In object-oriented programming, a problem is viewed in terms of the following concepts :


 Objects
 Classes
 Data Abstraction
 Data Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

The difference between object oriented program and structured program is as follows:

Object Oriented programming is a superset of structured programming.


Structured programming is as follows :

--- Program start


var
var
var

function { ... }
function { ... }
function { ... }

main { ... }
--- Program End

There are units of code, which operate on variables, and are called in reference to those variables, to
follow a structure acting on those variables.

Object oriented programming is as follows:

--- Program Start


object
{
var
var
function { ... }
function { ... }
function { ... }
}

34
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

var
var

function { ... }
main { ... }
--- Program end

Variables can be objects, which have their own data and functions.  Structures can have functions
"in them" which operate specifically on their own data. In object-oriented programming, instead of
creating units of data to pass to functions which operate on them, we create objects and have them
perform operations [on themselves].
Structured Language is command-line friendly, whereas, OOPs is user(Developer) friendly.

Q. What is the structure of C++ program? Summarize the steps involved in executing an application
program written in C++?
Ans:

The structure of a C++ program that uses object-oriented approach of programming has usually
three sections:
 Compiler directives
 Classes
 Main function

Note that a C++ program must have one and only one main function. The main function can also be
a part of a class.

#include <iostream.h>
#include <conio.h> Compiler directive section
#include “myclass.h”

class Vehicle
{ attribute1; attribute2;
public : Class section
fun1();
fun2();
};
void main()
{ }

A C++ program may be contained completely in one source file or may be split across many source
files. Separate source files can be compiled producing individual object files, which can be linked to
produce a single application.

There are three steps, viz., creating, compiling, linking and running the program that involved in
executing an application program written in C++ language.

Creating a C++ program


To create a C++ program,
Select File  New to open a blank file in Turbo C++ (most commonly used).
Type the program in the file.
Click File  Save that will open a dialog box. Here, browse for the directory where to save and
enter the filename. Click OK to save the file which will take the .CPP entension automatically, say,
Test.cpp.

35
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Compiling a C++ program


Compiling a C++ program depends on the compiler as well as the operating system under use.
With Turbo C++ compiler on DOS platform, the compilation of the Test.cpp file will be as given
below:

C:\>tcc Test.cpp

Here, TCC is the name of the Turbo C++ compiler. The compilation would produce an object file
called Test.obj. Object files, thus produced, contain the machine language translation of the C++
program.
The compiling can also be done by clicking Compile from the menu or pressing Alt + F9 key.

Linking a C++ program


To make the file executable, it is necessary to link the object files with library files, when Test.exe
is produced.
To link the file, select Compile --> Link from the menu, that will produce the Test.exe.

Running a C++ program


Now to run the C++ program, click Run from the menu. This will run, i.e., execute the program. To
see the output, click Alt+F5.

Q. What is encapsulation? What are its advantages? How can encapsulation be enforced in C++?
Ans:
The wrapping up of data and member function into a single unit is called encapsulation. The data is
not accessible to the outside function and only those functions that are wrapped into a class (the
single unit) can access it. Hence, using the method of encapsulation, the programmer cannot directly
access the data.

The advantages of data encapsulation are as follows:

 The data and functions bundled inside the class take total control of maintenance and thus human
errors are reduced.

 Although encapsulated objects provide functionality, the calling objects will not know the
implementation details. The access specifier acts as the key strength behind the concept of security
and provides access to members of class as needed by users. This prevents unauthorized access and
enhances the security of the application.

 The keywords or the access specifiers can be placed in the class declaration as ‘public’, ‘protected’
or ‘private’.
A class placed after the keyword ‘public’ is accessible to all the users of the class. The elements
placed after the keyword ‘private’ are accessible only to the methods of the class. In between the
public and the private access specifiers, there exists the ‘protected’ access specifier. Elements
placed after the keyword ‘protected’ are accessible only to the methods of the class or classes
derived from that class. Thus, it improves understandability of the program.

 Complex and critical applications are difficult to maintain. The cost associated with maintaining the
application is higher than that of developing the application properly. The conception of
encapsulating related data and functions into a single class makes the maintenance much easier on
the class level.

 Another advantage of using object-oriented encapsulation is for code re-usability. If we encapsulate


say a database object, it might have some internal method called "search". Every instance of that
object will now have the ability to search itself for information, and we have only written the
function once.

36
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Differentiate and give examples to bring out the difference between default constructor and copy
constructor.
Ans:

Default Constructor Copy Constructor


1. A constructor with default argument is default 1. A copy constructor allows an object to be
constructor. It is used to initialize object with initialized with another object of the same
user-defined parameters at the time of creation. class. It implies that the values stored in data
members of an existing object can be copied
into the data variables of the object being
constructed, provided the objects belong to
the same class.
2. A default constructor takes one or more than 2. A copy constructor has a single parameter
one parameter at the time of creation. of reference type that refers to the class
itself.

Example of Default Constructor

constructor :: interest ( );
interest i1(1000, 2);
interest i2(1000, 2, 15);

Here, the default constructor is interest without any argument. The data members principal and year
of object i1 are initialized to 1000 and 2 respectively at the time when object i1 is created.

Example of Copy Constructor

Let us create an object myabc1 with two integer parameters:


abc myabc1(1, 2);

Now , we can create another object of abc type, say myabc2 from myabc1:
myabc2 = abc(& myabc1);

Thus, the data values of myabc1 will be copied into the corresponding data variables of object
myabc2.

Q. Differentiate between public and private access specifies with suitable examples.
Ans:
Access specifiers are used to identify access rights for the data and member functions of the class.

A ‘private’ member within a class denotes that only members of the same class have accessibility,
and is not accessible from outside the class. ‘Private’ is the default access level for specifiers, i.e., if
no access specifiers are identified for data members of a class, the data members are defaulted to
private access.

‘Public’ members are accessible from outside the class. It is the default access specifier for member
functions, i.e., if no access specifiers are identified for member functions of a class, the functions
are defaulted to public access.

The following program shows the difference clearly:

class Base
{

37
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

public:
int m_nPublic;
private:
int m_nPrivate;
};

class Pub: public Base


{
//Public inheritance means:
//m_nPublic stays public
//m_nPrivate stays private

Pub()
{
//The derived class always uses the immediate parent's class access
specifications
//Thus, Pub uses Base's access specifiers

m_nPublic = 1; // okay: anybody can access public members


m_nPrivate = 2; // not okay: derived classes can't access private members in
the base class!
}
};

int main()
{
// Outside access uses the access specifiers of the class being accessed.
// In this case, the access specifiers of cPub. Because Pub has inherited publicly from
Base

Pub cPub;
cPub.m_nPublic = 1; // okay: anybody can access public members
cPub.m_nPrivate = 2; // not okay: can not access private members from outside class
}

In the code above, the member ‘m_nPrivate’ is defined as ‘private’ access specifiers, and
‘m_nPublic’ is defined as ‘public’ access specifier. The features of the public and private access
specifiers have been illustrated in the comment lines of the given program.

Q. Explain abstract base class.


Ans:
An abstract base class can be defined as something that will not be used to create any object, but
exits only to act as a base class of other classes. A class, to be abstract, must contain at least one
pure virtual function.

The following is an example of an abstract class:


class AB
{
public:
virtual void f() = 0;
};

An abstract class cannot be used as a parameter type, a function return type, or the type of an
explicit conversion. Also it is not possible to declare an object of an abstract class. However,
pointers and references to an abstract class can be declared. Virtual member functions are inherited.

38
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

A class derived from an abstract base class will also be abstract unless we override each pure virtual
function in the derived class.

For example:

class AB
{
public:
virtual void f() = 0;
};

class D2 : public AB
{
void g();
};

int main()
{
D2 d;
}

The compiler will not allow the declaration of object d because D2 is an abstract class; it
inherited the pure virtual function f()from AB. The compiler will allow the declaration of
object d if you define function D2::g().
We can derive an abstract class from a non-abstract class, and can override a non-pure
virtual function with a pure virtual function.

Q. Neatly explain constructor and destructor with suitable example.


Ans:
Constructor is a public method that is called automatically when the object of a particular class is
created. A constructor creates an object, allocates memory space to the data members and initializes
the data members to appropriate values at the time of object creation.
C++ provides a default constructor method without any parameter to all the classes. This is possible
as the default constructor method has been defined in ‘system.object’ class, and since every class is
an extension of ‘system.object’ class, so this method is inherited by all the classes. A default
constructor just initializes the data variables of the object to valid initial values.
While defining a constructor, the following points are to be noted:

1. The name of constructor method must be the same as the class name in which it is defined.
2. A constructor method must be a public method.
3. Constructor method does not return any value.
4. A constructor method may or may not have parameters.

An example of defining a constructor is shown in the below given program:

class abc
{
int x,y;
public:
abc(int, int);
}
abc : : abc(int a, int b)
{
x = a;

39
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

y = b;
}
main()
{
abc myabc(100, 200);
---
}

Here, the class ‘abc’ has a constructor ‘myabc’ that accepts two parameters of integer type.

Destructor does just the opposite task of the constructor when the program creating an object exits,
thereby freeing the memory. A destructive method has the following characteristics:

1. Name of the destructor method is the same as the name of the class preceded by a tilde (~).
2. The destructor method does not take any argument.
3. It does not return any value.

The example of a destructor is shown in the below given program:

class abc
{
int x,y;
public:
abc();
abc(int);
abc(int, int);
~abc()
{
cout << “Object being destroyed!!”;
}
}

Here, “~ abc()” is the destructor called to destroy the object abc.

Q. What is a static member function? Explain with an example.


Ans:

We cannot have static and non-static member functions with the same names and the same
number and type of arguments.

Like static data members, one may access a static member function f() of a class A
without using an object of class A.

A static member function does not have a this pointer. The following example
demonstrates this:

#include<iostream>
using namespace std;

struct X
{
private:
int i;
static int si;
public:

40
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void set_i(int arg) { i = arg; }


static void set_si(int arg) { si = arg; }

void print_i() {
cout << "Value of i = " << i << endl;
cout << "Again, value of i = " << this->i << endl;
}

static void print_si()


{
cout << "Value of si = " << si << endl;
//cout << "Again, value of si = " << this->si << endl;
}

};

int X::si = 77; // Initialize static data member

int main()
{
X xobj;
xobj.set_i(11);
xobj.print_i();

// static data members and functions belong to the class and


// can be accessed without using an object of class X
X::print_si();
X::set_si(22);
X::print_si();
}

The following is the output of the above example:


Value of i = 11
Again, value of i = 11
Value of si = 77
Value of si = 22
The compiler does not allow the member access operation this->si in function
A::print_si because this member function has been declared as static, and therefore
does not have a this pointer.
We can call a static member function using the this pointer of a nonstatic member function.
In the following example, the nonstatic member function printall() calls the static
member function f() using the this pointer :
#include<iostream>
using namespace std;

class C
{
static void f() {
cout << "Here is i: " << i << endl;
}
static int i;
int j;
public :
C(int firstj) : j(firstj) { }

41
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void printall();
};

void C::printall()
{
cout << "Here is j: " << this->j << endl;
this->f();
}

int C::i = 3;

int main()
{
C obj_C(0);
obj_C.printall();
}

The following is the output of the above example:

Here is j: 0
Here is i: 3

A static member function cannot be declared with the keywords virtual, const, volatile, or
const volatile.

A static member function can access only the names of static members, enumerators, and
nested types of the class in which it is declared. Suppose a static member function f() is a
member of class X. The static member function f() cannot access the nonstatic members X
or the nonstatic members of a base class of X.

Q. Explain the use of this pointer.


Ans:
C++ uses a unique keyword called “this” to represent an object that invokes a member function. The
‘this’ pointer points to the object for which this function was called. This pointer is called and it
passes to the member function automatically. Thus, it acts as an implicit argument to all the member
function.
#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
using namespace std;

class person
{
char name[25];
float age;
public:
//person(){};
person(char *s,float a)
{
strcpy(name,s);
age = a;

42
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

}
person& person::greater(person &x)
{
if(x.age>= age)
{
cout<<"\nObject reference Used : "<<&x<<endl;
return x;
}
else
{
cout<<"\nObject reference Used Here : "<<this<<endl;
return *this;
}
}
void show()
{
cout<<"Name : "<<name<<" and Age : "<<age;
}
};

int main()
{
clrscr();
person p1("Anil",37.5);
person p2("Ahmed",49.0);
person p3('\0',0.00);
cout<<"Object reference of p1 : "<<&p1<<endl;
cout<<"Object reference of p2 : "<<&p2<<endl;
p3=p1.greater(p2);
cout<<"\nObject reference of p3 : "<<&p3<<endl;
cout<<"\nGreater value is... ";
p3.show();
getch();
}

Q. Show a use of extern storage class specifier.


Ans:
The extern storage class specifier allows to declare objects and functions that several source
files can use. An extern variable, function definition, or declaration makes the described
variable or function usable by the succeeding part of the current source file. This
declaration does not replace the definition. The declaration is used to describe the variable
that is externally defined.
An extern declaration can appear outside a function or at the beginning of a block. If the
declaration describes a function or appears outside a function and describes an object with
external linkage, the keyword extern is optional. If we do not specify a storage class
specifier, the function is assumed to have external linkage.
The keyword extern affects the linkage of a function or object name. If a declaration for an
identifier already exists at file scope, any extern declaration of the same identifier found
within a block refers to that same object. If no other declaration for the identifier exists at
file scope, the identifier has external linkage.

Example 1:

#include<stdio.h>

43
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

#include<conio.h>

main()
{
extern i; //i is declared as extern
printf("\nTesting.........");
printf("\nvalue of i=%d",i);//we are accessing the value of i with out specifying any
value of type of i
getch();
}
int i=45;//value of i and it's type is given here

Example 2 :
File 1: “myheader.h”

int i=45;

File 2:
#include<stdio.h>
#include<conio.h>
#include "myfile.h"

/* definition of i is given in the external file myfile.h which is included using


"myfile.h" */
main()
{
extern i; //i is declared as extern
printf("\nTesting.........");
printf("\nvalue of i=%d",i); //we are accessing the value of i with out
//specifying any value of type of i
getch();
}

TOPIC : INHERITANCE
--------------------------------------
Short Answer Questions
--------------------------------------

Q. Differentiate between class inheritance and embedding.


Ans:

Class Inheritance Class Embedding


The class is derived from base class. The class exists in the base class.
The class may or may not be static. The class must not be declared as static.
Inheritance strictly supports protected For Embedding the protected security may be
specifier. violated.
This feature can make class Hierarchy. This feature cannot make class Hierarchy.

Q. Describe the meaning of multiple inheritance?


Ans:
A class can be derived from any number of base classes. The technique of deriving a class from two
or more direct base classes is called multiple inheritance.

44
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

In the following example, classes A, B, and C are direct base classes for the derived class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };

The following ‘inheritance graph’ describes the inheritance relationships of the above example. An
arrow points to the direct base class of the class at the tail of the arrow:

A direct base class cannot appear in the base list of a derived class more than once.

--------------------------------------
Long Answer Questions
--------------------------------------

Q. How does C++ support Inheritance?


Ans:
C++ strongly supports the concept of reusability. The C++ classes can be used in several ways.
Once a class has been written and tested, it can be adopted by other programmers. This is basically
created by defining the new classes, reusing the properties of existing ones. The mechanism of
deriving a new class from an old one is called ‘INHERITENCE’. The old class is called ‘BASE’
class and the new one is called ‘DERIVED’ class.

The general syntax of defining a derived class is as follows :

class a_classname : Access specifier baseclass name


{

//members of derived class
...

};

The colon indicates that the a-class name is derived from the base class name. The access specifier
or the visibility mode is optional and, if present, may be public, private or protected. By default it is
private. Visibility mode describes the status of derived features, e.g.,

class xyz //base class


{
members of xyz
};
class ABC : public xyz //public derivation
{
members of ABC
};
class ABC : XYZ //private derivation (by default)
{

45
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

members of ABC
};

C++ supports different types of inheritance:-

Single Inheritance: A class can inherit properties from more than one class or from more than one
level. A derived class with only one base class is called single inheritance.

Public Inheritance: When the access specifier for a base class is public, all public members of the
base become public members of the derived class.

Private Inheritance: When the base class is inherited by using the private access specifier, all
public and protected members of base class become private members of the derived class.

Protected Inheritance: When the base class is inherited by using the protected access specifier, all
public and protected members of base class become protected members of the derived class.

Q. How inheritance occurs and works in different levels?


Ans:
The mechanism of deriving a new class from an old one is called inheritance (or derivation). The
old class is referred to as the ‘base class’ and the new one is called the ‘derived class’. The derived
class inherits all or some of the traits of the base class.
The general form of class inheritance is as follows:

Class derived-class-name : access base-class-name


{
// body of class
};

The inheritance is of different types: -

Single Inheritance : A derived class with only one base class is called single inheritance.

Public Inheritance : When the access specifier for a base class is public, all public members of the
base become public members of the derived class.

Private Inheritance : When the base class is inherited by using the private access specifier, all
public and protected members of base class become private members of the derived class.

Protected Inheritance : When the base class is inherited by using the protected access specifier, all
public and protected members of base class become protected members of the derived class.

Multilevel Inheritance : The type of inheritance where a class A serves as a base class for a
derived class B which in turn serves as a base class for the derived class C, then it is known as
‘Multilevel Inheritance’. The class B is called ‘Intermediate Base Class’ as it provided a link for the
inheritance between A and C. The chain ABC is called ‘Inheritance Path’.

Multiple Inheritance : The mechanism by which a class inherits the attributes of two or more
classes is known as Multiple Inheritance.

The below given program shows all types of inheritances :

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

46
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

class student
{
public:
int rno;

public:
void get()
{
cout<<"\n\nEnter the Roll No:";
cin>>rno;
}
};

class test1 : public virtual student


{
protected:
float score1;

public:
void get1()
{
cout<<"\n\n1st test score <strong class="highlight">of</strong> "<<rno<<" is :";
cin>>score1;
}
};

class test2 : public virtual student


{
protected:
float score2;

public:
void get2()
{
cout<<"\n\n2nd test score <strong class="highlight">of</strong> "<<rno<<" is :";
cin>>score2;
}
};

class avg : public test1, public test2


{
public:
int average;

public:
void result()
{
average=int((score1+score2)/2);
}
};

class disp : public avg


{
public:
void display()

47
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

{
cout<<"\n\nThe result <strong class="highlight">of</strong> "<<rno<<" is "<<average;
}
};

int main()
{
disp k;
k.get();
k.get1();
k.get2();
k.result();
k.display();
return 0;
}

Q. Write C++ syntax to declare that a class B is derived from class A.


Ans:

From a base class child class can be derived in two way.


i) Child class can be derived publicly.
In this case all the properties and functions of public part of the base class come to the
public part of child class.
Example:
class A
{
private:
int ipra;
void funpra(void);
public:
int ipba;
void funpba(void);
}
class B: public A
{
private:
int iprb;
void funprb(void);
public:
int ipbb;
void funpbb(void);

}
In this case the variables and functions of the public part of class A will come to the public
part of class B.

ii) Child class can be derived privately.


In this case all the properties and functions of public part of the base class come to the
private part of child class.
Example:
class A
{
private:

48
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

int ipra;
void funpra(void);
public:
int ipba;
void funpba(void);
}
class B: private A
{
private:
int iprb;
void funprb(void);
public:
int ipbb;
void funpbb(void);

}
In this case the variables and functions of the public part of class A will come to the private
part of class B.

NB: The private part of the base class can never be derived in the child class.

TOPIC : INTRODUCTION TO OOPS & C++

--------------------------------------
Short Answer Questions
--------------------------------------
Q. Give an example of how can encapsulation be enforced in C++

class test
{
int a;
}
int main(void)
{
test t;
t.a=100; //Here an error will be shown
}

We do not invoke any type of access specifier with in the class test.
But, we can not access the variable a of the object t of the class test from the out side function main( ).
Because the variable a is by default private here. So, the encapsulation is enforced in C++.
In order to work this out we can do the following :
class test
{
int a;
public : setA(int x){ a = x; }
getA(){ return a;}
}
int main(void)
{ int x;
cin>>x;
test t;
t.setA(x);
t.getA();
}

49
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Here, we can access the variable a using public member functions like setA() & getA().

Q. Define Data Abstraction, Message Passing.


Ans:
Data Abstraction : Abstraction refers to the act of representing essential features without including
the background details or explanations. Abstraction is indispensable part of the design process and
is essential for problem partitioning. Partitioning essentially is the exercise in determining the
components of the system. However, these components are not isolated from each other, they
interact with each other. Since the classes use the concept of data abstraction, they are known as
Abstract Data Types (ADT).

Message Passing : Message passing is another feature of object-oriented programming. An object-


oriented program consists of a set of objects that communicate with each other. The concept of
message passing makes it easier to talk about building systems that directly model or simulate their
real-world counter-parts.
A message for an object is a request for execution of a procedure, and therefore will invoke
a function in the receiving object that generates the desired result. Message passing involves
specifying the name of the object, the name of the function (message) and the information to be
sent.

Q. What do you mean by data hiding in C++?


Ans:
C++ provides a feature by which all the data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it. These functions provide the interface
between the object’s data and the program. This insulation of the data from direct access by the
program is called data hiding or information hiding.

Q. What is functional programming?


Ans:
Functional programming is a style of programming that emphasizes the evaluation of expressions
rather than the execution of commands. Conventional programming, using high level languages
such as COBOL, FORTRAN and C, is commonly known as ‘functional programming’ or
‘procedure-oriented programming’. In the procedure-oriented approach, the problem is viewed as a
sequence of things to be done such as reading, calculating and printing. Numerous functions are
written to accomplish these tasks.

Q. What is the benefit of code reuse?


Ans:
The benefit of code reuse is that we can add additional features to an existing class without
modifying it, which is possible by deriving a new class from the existing one. The new class will
have the combined features of both the classes. Each subclass defines only those features that are
unique to it.

Q. Differentiate between bottom up and top down testing.


Ans:
The difference between the bottom up and top down testing are as follows:

(I) Top down design proceeds from the abstract entity to get the concrete design.
Bottom up design proceeds from the concrete design to get to the abstract entity.

(II) Top down design is most often used in designing brand new systems, while bottom up design is
sometimes used when one is reverse engineering a design; i.e., when one is trying to figure out what
somebody else designed in an existing system.

50
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

(III) Bottom up design begins the design with the lowest level modules or subsystems, and
progresses upward to the main program, module, or subsystem. With bottom up design, a structure
chart is necessary to determine the order of execution, and the development of drivers is necessary
to complete the bottom up approach.
Top down design, on the other hand, begins the design with the main or top-level module, and
progresses downward to the lowest level modules or subsystems.

(IV) Real life sometimes is a combination of top down design and bottom up design. For instance,
data modeling sessions tend to be iterative, bouncing back and forth between top down and bottom
up modes, as the need arises.

--------------------------------------
Long Answer Questions
--------------------------------------

Q. There are so many object-oriented languages available today, but why C++ become more popular?
Ans:
Although there are many object-oriented languages available today, C++ is more popular for the
following reasons :

 C++ enables programmers to build large programs with clarity, extensibility, efficiency and ease of
maintenance.
 The overloading (operator and function) feature of C++ enables to create abstract data types inherit
properties from existing data types and support polymorphism.
 Since C++ allows to create hierarchy-related objects, special object-oriented libraries can be
developed that can be used later by many other programmers.
 It is quite efficient to map the real-world problem properly, thus making the program close to the
machine-level details.
 When a new feature needs to be implemented, it is very easy in C++ to add to the existing structure
of an object.
 It provides a great feature ‘encapsulation’ that binds the data and member function together to make
the coding more portable, reliable and cost-effective.
 It involves ‘polymorphism’, the attribute that allows one interface to control access to a general
class of actions.
 Another feature is ‘Inheritance’ by which one object can acquire the properties of another object.
This is important as it supports the concept of classification.
 C++ provides ‘modular’ feature, means, each source file needs to be compiled only once and if we
make a change in one file out of the 100+ files in a project, only that file is compiled and then
linked to the rest of the project.

Q. Compare functional programming and object-oriented programming.


Ans :

Functional Programming Object-oriented Programming


1. Functions, constants and variables are the raw 1. Objects(data) are typically the non-
materials of processing & to be understood in constant state. Variables are storage
the mathematical sense. locations in memory that may hold different
values at different times; and Methods
(operations) on objects’ data that may or
may not change the objects state.
2. The result of a function depends only on its 2. The result of a method should depend only
arguments and the context at on its arguments and the object’s state at

51
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

function definition time. method invocation time.


3. In functional programming everything is 3. In object-oriented programming almost
basically a set of functions each of which everything is treated as an object that can be
performs a separate task. Selectively executing modified and has its nature/tasks defined
these function results in the solution to the within itself, or it can be said that objects
problem in hand. have state and behavior. It provides
modularity, data abstraction & data hiding.
4. Data can move freely around across systems 4. Data movement is restricted & can only be
from function to function. allowed selectively if required.
5. Functions transform data from one form to 5. New data and functions can be easily
another. added to existing one whenever necessary
incurring least overhead.
6. Employs top-down approach in program 6. Follows bottom-up approach in program
design. design.

Q. What are benefits provided by the object-oriented programming (OOP)?


Ans:
Object-oriented programming provides imparts facilities to the development and quality of software
products. The technology provides better quality of software, lesser maintenance cost and thereby better
productivity. OOP provides the following main advantages:

 Through inheritance, redundant code can be eliminated and the use of existing classes can be
extended.

 Programs can be built from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This saves the development time and
increases productivity.

 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.

 It is possible to map objects in the problem domain to those objects in the program.

 It is easy partition the work in a project based on objects.

 The data-centered design approach enables to capture more details of a model in implementable
form.

 Object-oriented systems can be easily upgraded from small to large systems.

 Message passing techniques for communication between objects makes the interface descriptions
with external systems much simpler.

 Software complexity can be easily managed.

Q. Write the advantages & disadvantages of C++.


Ans:
The advantages of C++ are as follows:

52
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

 C++ provides excellent object oriented features. Thus, it makes the coding of compilers,
interpreters, design tools, and even operating systems easier.

 C++ is a multiparadigm language. This allows developers to choose the programming style that is
right for the task at hand. For example, a traditional procedural style may be appropriate for
performing a simple task such as writing the code within a small member function.

 It also enables to code communication protocols in C++.

 Some software need more frequent upgradation than others. Such a software is the Games software
that are frequently updated to make more realistic and interesting for which C++ is necessary being
performance and memory efficient.

 Database systems are fast moving towards object-oriented pattern. C++ is a very popular choice for
database and similar systems.

The disadvantages of C++ are as follows :

 Does not provide very strong type-checking. C++ code is easily prone to errors related to data types,
their conversions, say, while passing arguments to functions.
 Does not provide efficient means for garbage collection, as already mentioned.
 No built in support for threads.
 Gets complex when need to develop a graphics rich application in C++.
 Portability of code on various platforms, etc.
 Not pure object oriented programming language, as it doesn’t support for proper garbage collection
that has been overcome by Java.

TOPIC : FUNCTION, STRING OPERATION

--------------------------------------
Short Answer Questions
--------------------------------------

Q. Explain the differences between passing arguments “by reference” and “by addresses” to
functions.

Ans:
Passing arguments “by reference” Passing arguments “by addresses”
1. The reference of object is passed as a 1. The address of object is passed as a function’s
function’s argument. argument.
2. A bit-field cannot be referenced. 2. Bit-field can be addressed.
3. Null references are prohibited. 3. Null address can pass through function’s
argument.
4. <return_type>< 4. <return_type> <fun_name>( <class_name> *
fun_name>( <class_name> & <var_name>) <var_name>)

Q. Write down the uniqueness of inline functions.


Ans:
Unlike normal functions, effective code length of the compiled code increases with each call of the
inline function. Also, invocation of the inline function is faster than the normal function. Lines of
code in an inline function are encouraged to keep less in number.

Q. What are function prototypes?

53
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Ans:
A function prototype in C++ is a declaration of a function that omits the function body but does
specify the function's name, number of arguments or operands that the function takes (or, the
number of domains in the corresponding Cartesian product), argument types and return type. While
a function definition specifies what a function does, a function prototype specifies its interface.
In a prototype, argument names are optional, however, the type is necessary along with all
modifiers (i.e., if it is a pointer or a const argument).
For example:
int fac(int n);

This prototype specifies that there is a function named "fac" which takes a single integer argument
"n" and returns an integer. Elsewhere in the program a function definition must be provided if need
to use this function.

Q. When would a function prototype contain a parameter type declaration such as “double &”?
Ans:

If we want to pass a reference of a double with in a function’s parameter, then the parameter of the
function will be declared as “double &”.

Q. Distinguish between the terms “function template” and “function template specialization”.
Ans:

Function Template Function Template Specialization


1. A ‘function template’ behaves like a 1. The programmer may decide to implement a
function that can accept arguments of many special version of a function (or class) for a certain
different types. In other words, a function type which is called ‘function template
template represents a family of functions. specialization’.
2. Function templates cannot be partially 2. If a function template specialization contains a
specialized. subset of its parameters it is called ‘partial template
specialization’. If all of the parameters are
specialized it is an ‘explicit specialization’ or ‘full
specialization’.

Q. Explain when to use references and when pointers.


Ans:
References are used in function parameter lists, where they allow passing of parameters used for
output with no explicit address-taking by the caller.
For example:
void square(int x, int& result)
{
result = x * x;
}

Then, the following call would place 9 in y:


square(3, y);

In many implementations, normal parameter-passing mechanisms often imply an expensive copy


operation for large parameters. References qualified with ‘const’ are a useful way of passing large
objects between functions that avoids this overhead.

Pointers are used as the faster means of accessing arrays. A pointer is a special variable that return
the address of a memory. So, it is used to get the address of a memory. Sometimes it is implemented
so that the function in C++ can modify the parameters passed to it.

54
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. What are the disadvantages of using friend functions?


Ans:
The major disadvantage of friend functions is that they require an extra line of code when you want
dynamic binding. To get the effect of a virtual friend function, the friend function should call a
hidden (usually protected) virtual member function. Another disadvantage is that a class which is
declared as ‘friend’ has the right to access as many members of the main class, thereby reduces the
level of privacy of the data encapsulation.

Q. What error message will you receive when the function “void f(void) {return (1)}” is compiled?
Ans:

The error message will be: “Can not return a value”


Explanation: Here the return type of the function f() is void and so it can not return any value.

Q. Evaluate the function f(n) = f(n – 2) * f(n – 1), f(0) = f(1) = 1 for n = 5.
Ans:
f(5) = f(3)*f(4)
 f(5) = {f(1)*f(2)}*{ f(2)*f(3)} [Since 3 and 4 both are greater than 0&1]
 f(5) = [f(1)*{f(0)*f(1)}]*[{f(0)*f(1)}*{f(1)*f(2)}] [Since 2 and 3 both are greater than 0&1]
 f(5) = [f(1)*{f(0)*f(1)}]*[{f(0)*f(1)}*{f(1)*f(0)*f(1)}] [Since 2 is greater than 0&1]
 f(5) = f(1)*f(0)*f(1)*f(0)*f(1)*f(1)*f(0)*f(1) [Removing Brackets]
 f(5) = 1*1*1*1*1*1*1*1 [Since f(0) = f(1) = 1]
 f(5) = 1
Hence the value of the expression is 1.

Q. Which built-in functions are used in dynamic memory allocation?


Ans:
The ‘new()’ and ‘delete()’ operators are built-in functions that are used in dynamic memory
allocation.

Q. What is inline function?


Ans:
An inline function is just a function whose declaration is accompanied with its definition. It
provides a reduced execution time in the code.
With the normal functions, the compiler puts a jump instruction to the code when a function is
called. This means that arguments and automatic variables have to be set up on the stack and the
program execution has to be transferred to the function itself. But, with the use of inline functions,
the computer actually puts the entire code for the function directly into the code that is inline. That
means, no jump is needed that saves time. However, the program size increases as the same code is
copied many times whenever the inline function is called.
To create an inline function, ‘inline’ keyword is required at the beginning of function prototype as
shown below:
inline int sum(int, int);

Q. Write a recursive function for

Ans:
int fun(int a)

55
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

{
if(a= =1)
{
return 1;
}
else
{
return(2*fun(a-1));
}
}

--------------------------------------
Long Answer Questions
--------------------------------------
Q. Create String Comparison, String Concatenation and String Length functions using pointers.
Ans:

String Comparison:
int strcmp(char *x,char *y)
{
int i,j;
for(i=0;x[i]!='\0';i++);
for(j=0;y[j]!='\0';j++);
if(i!=j)
{
return -1;
}
else
{
j=0;
for(i=0;x[i]!='\0';i++)
{
if(x[i]!=y[i])
{
j++;
}
}
return j;
}
}
This function will return a value 0, if the strings are matched, other wise it will return non zero
value.

String Concatenation
void strconcat(char *x, char *y)
{
int i,j;
for(i=0;x[i]!='\0';i++);
for(j=0;y[j]!='\0';j++)
{
x[i] = y[j];
i++;
}
x[i]='\0';
}

56
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

This function will take two string and assign the whole second string after the first string, taken.

String Length :
int strlength(char *x)
{
int i;
for(i=0;x[i]!='\0';i++);
return i;
}
This function will take a string’s base address and return the length of the string as integer.

Q. What is a member function? Can two classes contain member functions with the same name?
Ans:
Member functions are operators and functions that are declared as members of a class. Member
functions do not include operators and functions declared with the friend specifier.

A member function is defined outside the class using the :: (double colon symbol) scope resolution
operator. The general syntax of the member function of a class outside its scope is:

<return_type> <class_name> :: <member_function> (arg1, arg2, …., argN)

The type of member function arguments must exactly match with the types declared in the class
definition of the <class_name>. The Scope resolution operator (::) is used along with the class name
in the header of the function definition. It identifies the function as a member of a particular class.

Yes, two classes contain member functions with the same name. Not only the name, the definition
of the functions can be also same. Even more the both classes, containing the functions with same
name can be of same class hierarchy. e.g.,

#include<iostream.h>
#include<conio.h>
class test1
{
int i1;
public :
void fun(void)
{
cout<<"MySite";
}
};
class test2
{
int i2;
public :
void fun(void)
{
cout<<"Mysite";
}
};
int main(void)
{
int i=10;
return i;
}

57
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. What is a template function in C++?


Ans:
A template function defines how a group of functions can be generated. Function templates are
special functions that can operate with generic types. They can handle different data types without
separate code for each of them. This allows 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. For a similar
operation on several kinds of data types, a programmer need not write different versions by
overloading a function, as it is enough writing a C++ template based function. This will take care of
all the data types.

template <class T>


T Add(T a, T b) //C++ function template sample
{
return a+b;
}

Here T is the typename. This is dynamically determined by the compiler according to the parameter
passed. The keyword class means, the parameter can be of any type, even be a class.

TOPIC : ARRAY

--------------------------------------
Short Answer Questions
--------------------------------------

Q. How will you create a 2D array at run time?


Ans:
To create a 2D array at run time we can apply the following code :
void main()
{
int **a;
int rows = 3, cols = 4; //3X4 matrix
a = new int*[rows];
for(int i = 0; i<rows; i++)
*(a + i) = new int[cols];

}

Q. For a two-dimensional array int a[2][2], which element is represented by **(a+1)?.


Ans:

The answer will be a[1][0].

Q. How are the elements of one-dimensional array stored and accessed?


Ans:

The one-dimensional array is stored and accessed by the help of loop.

Storing an array :
int a[10];
for(int i =0; i<10; i++)
{
cin>>a[i];
}

58
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Reading from an array :


int a[10];
for(int i =0; i<10; i++)
{
cout<<a[i];
}

Q. How will you initialize an array of n strings?


Ans:

An array of n strings can be implemented by a 2D character array as follows :

void main()
{ int i = 0;
char arrStr[2][30] = {“Brainware”,”PTU”}; //initialization
printf("%s", arrStr[0]);
printf("%s", arrStr[1]);
}

Q. What is the difference between the expressions a4 and a[4]?


Ans:
The expression a4 means a variable with the name ‘a4’ and it can store one only one value. That
means, only one memory space will be allocated for this variable. The size of memory space will
depend on the type of the variable.
The expression a [4] means an array with 4 elements, whose base address is a. It can store 4
elements in contagious memory location. The size of memory space will depend on the type of the
array.

--------------------------------------
Long Answer Questions
--------------------------------------

Q. What is an array? Describe briefly about various types of array.


Ans:
An array is a named list of a finite number of similar data elements. Each of the data elements can
be referenced respectively by a set of consecutive numbers, usually 0, 1, 2, 3, ….n. If the name of
an array of 10 elements is ARY, then its elements will be referenced as shown below:
ARY[0], ARY[1], ARY[2], ARY[3], …., ARY[10]

The element numbers in parenthesis are called subscripts or indices. The subscript, or index of an
element designates its position in the array’s ordering.

There are three types of arrays, viz., one-dimensional, two-dimensional and multi-dimensional.

One-Dimensional Array: It is the simplest form of an array. The array itself is given a name and its
elements are referred to by their subscripts. The syntax to use this array is Arrayname [size] ,
where ‘size’ specifies the number of elements in the array and the subscript (or index) value range
from 0 to size.
For example, int array[2] = {1, 2};

Two-Dimensional Array: It is an array in which each element is itself an array.


For instance, an array A [1---m, 1---n] is an M by N table with M rows and N columns containing
MxN elements.
The number of elements in a 2-D array can be determined by multiplying the number of
rows with the number of columns.

59
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

For example, static int table[2][3] = {0, 0, 0, 1, 1, 1};

Multi-Dimensional Array: In this type of array, each element is an array. For instance, an array
A [1---p, 1---q, 1---r] is a multi-dimensional array.
For example, static int arr[3][4][2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6}, },
{{7, 6}, {3, 4}, {5, 3}, {2, 3}, },
{{8, 9}, {7, 2}, {3, 4}, {6, 1}, }
};

In this array, the outer array is an array of three elements, each of which is a two-dimensional array
of four rows, each of which is a one-dimensional array of two elements.

TOPIC : POLYMORPHISM

--------------------------------------
Short Answer Questions
--------------------------------------

Q. What is the use of virtual functions?


Ans:
A virtual function allows derived classes to replace the implementation provided by the base class.
The compiler makes sure the replacement is always called whenever the object in question is
actually of the derived class, even if the object is accessed by a base pointer rather than a derived
pointer. This allows algorithms in the base class to be replaced in the derived class, even if users
don't know about the derived class.

The derived class can either fully replace ("override") the base class member function, or the
derived class can partially replace ("augment") the base class member function. The latter is
accomplished by having the derived class member function call the base class member function, if
required.

For example :

class base
{
public:
       virtual int multiply(int x, int y);
};
class derived : public base
{
  public:
     float multiply(float x, float y);
};

derived d;
d.multiply(10,2); //this method called from base class.

The result of the above set of code is 20.

Q. What is the difference between Static binding and Run-time binding? Explain with a suitable C++
code.
Ans:
Static Binding Run-time Binding

60
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

1. This binding is occurred at the compile 1. This binding is occurred at the run time of the
time of the program program
2. The binding cannot be changed during 2. This binding is a dynamic binding and it can
the program execution. change runtime.
3. Static binding facilitates structural 3. Run time binding facilitates more flexible and
software architectures. extensible software architectures.
4. the compiler uses the type of the pointer to 4. the decision is made at run-time based upon
perform the binding at compile time the type of the actual object.

Q. How many arguments are required in the definition of an overloaded binary operator?
Ans:
One argument is required in the definition of an overloaded binary operator.
E.g. : In context of ‘+’ operator operating on a complex class.

complex operator+(complex x)
{ /* here single argument : complex x present,
other operand is implicitly passed into the function
by reference, if we write real here it refers to the real value of c1(below)*/
complex c;
c.real = real + x.real;
c.imag = imag + x.imag;
return c;
}

call of the operator function :

complex c1, c2, c3;


c3 = c1+c2;

Q. What is a pointer variable? How are pointers important in a programming language? Give an
example of use of pointers in C++?
Ans:
A pointer variable is a special variable that return the address of a memory. The only difference
between a pointer variable and a regular variable is that a regular variable can contain values,
whereas a pointer variable does not contain values, but the address of a value. A pointer follows all
the usual naming rules of regular, non-pointer variables.
In a programming language, whenever we declare a variable, the system allocates,
somewhere in the memory, a memory location and a unique address is assigned to this location.
Hence, a pointer is very useful in order to hold the address of a memory location rather than the
value of the location. As the memory addresses are numbers, they can be assigned to some other
variable.
In C++, let us take an example of storing a value of 20 in a variable named ‘age’. Here, C+
+ store the value of 20 after reserving storage for the variable age. Now, suppose that it is required
to declare a pointer variable, not to hold the age, but to point to the variable age.

The following program example demonstrates the declaration and use of pointer in C++:

#include<iostream.h>
int main( )
{
int i = 20, *p_age;
p_age = &i;
cout<<i<< “ “<<*p_age<<endl;
}

In the above program, p_age is a pointer variable that hold the address of the integer variable i.

61
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

15. What is parameter passing? Explain with example call by reference scheme in C++.
Ans:
Parameter passing methods are the ways in which parameters are transferred between functions
when one function calls another. C++ provides two parameter passing methods—‘pass-by-
value’ and ‘pass-by-reference’.

A reference is an alias name for a variable. In C++, the call by reference method is useful in cases
where the values of the original variables are to be changed using a function.

An example of invoking a function call by reference

Let us take an example program to swap values of two variables using pass by reference method.

#include<iostream.h>
#include<conio.h> //for clrscr

int main()
{
clrscr();
void swap (int &, int &); //prototype
int a = 7, b = 4;
cout << “Original values \n”;
cout << “a = ” << a << “b = ” << b << “\n”;

swap(a, b); //invoke the function


cout << “swapped values \n”;
cout << “a = ” << a << “b = ” << b << “\n”;
return 0;
}

void swap (int &x, int &y) //function body


{
int temp;
temp = x;
x = y;
y = temp;
}

The output produced by the above program is as follows:

Original Values
a = 7, b = 4

Swapped Values
a = 4, b = 7

In the above program, the function swap() creates reference ‘x’ for the first incoming integers and
reference ‘y’ for the second incoming integer. Thus the original values are worked with but by using
the names x and y. The function call is simple as shown below:
swap (a, b);

But the function declaration and definition include the reference symbol ‘&’. The function
declaration and definition, both, start as

62
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void swap(int &, int &)

Therefore, by passing the references the function works with the original values (i.e., the same
memory area in which original values are stored) but it uses alias names to refer to them. Thus, the
values are not duplicated.

Q. Give operators that can’t be overloaded & also the reason for so.
Ans:
.(member selection), .*(member selection through pointer to function), ::(scope resolution), ?:
(conditional or ternary) are the operators that can’t be overloaded.
As a reason we can say that, usage of these Operators are reserved to be used only in single purpose
by the compilers.

Q. Differentiate between overloading and overriding.


Ans:
The differences between overloading and overriding are as follows :

Overloading Overriding
1. In Overloading, there is a relationship 1. In Overridding, there is relationship between
between methods available in the same class. a super class method and subclass method.
2. Overloading doesn't block inheritence from 2. Overridding blocks inheritence.
the superclass.
3. In Overloading, separate methods share the 3. In Overridding, subclass method replaces the
same name. superclass.
4. Overloading must have different method 4. Overriding must have same signature.
signatures
5. Overloading in C++ is the mechanism by 5. Overriding is the ability of the inherited class
which the language standard operators are rewriting the virtual method of the base class,
used for customized operations of the classes. i.e., redefining a function in a class is function
For example to write a string class, a very overriding.
simple "+" operator is used to handle string
concatenation, "-" for removing one part of
string from another, etc. This makes the Code
Reusability much easier. Method overloading
is the ability for functions of the same name to
be defined as long as these methods have
different signatures.
6. Overloading is compile time 6. Overridding is runtime polymorphism.
polymorphism.

--------------------------------------
Long Answer Questions
--------------------------------------
Q. When do you use virtual base class? Explain with an example.
Ans:
Let us consider the below given situation :
Parent

Child 1 Child 2

Grandchild

63
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Here, Base class is parent, and two derived classes are Child1 and Child2. Each of the Child1 and
Child2 inherits a copy of parents; such copy is known to be subobject. Every subobject contains its
own copy of parent’s data, including basedata. The fourth class Grandchild is derived from both
Child1 and Child2. It would have duplicate sets of the members inherited from the Parent. So, a
confusion may arise if a member function in the Grandchild class wants to access data or functions
in the parent class.
The duplication of inherited members due to these multiple paths can be avoided by making
the common base class (ancestor class) as ‘virtual base class’ while declaring the direct or
intermediate base classes as shown below:

class parent
{
protected :
int basedata;
};
class child1: virtual public parent //shares copy of parents { };
class child2 : virtual public parent //shares copy of parents { };
class Grandchild : public child1, public child2
{
class Grandchild: public child1, public child2
{
public:
int getdata ( )
{ return basedata; } // ok: only one copy of parents
};

Q. Write short note on the following:


(a) Polymorphism
(b) Friend functions
Ans:
(a) Polymorphism : Polymorphism refers to the implicit ability of a function to have different
meanings in different contexts. Let us consider the class hierarchy that contains Number and
ComplexNumber. If a number is defined as a pointer to Number then a Number can be instantiated
as either a Number or a ComplexNumber.

For example : Number *aNumber;


aNumber = new Number(1);
aNumber  output( );
delete aNumber;
aNumber  output( );
delete aNumber;

In the first case, the output function in Number would be called. In the second case, this function is
called again because a Number is a pointer to a Number and not a ComplexNumber.

(b) Friend functions: To make an outline function “friendly” to a class, this function is to be
declared as a ‘friend’ of the class. The function keyword should be preceded by the keyword friend,
and can be declared anywhere in the program. A friend function, although not a member function,
has full access rights to the private members of the class.

A friend function possesses following special features:


 It is not in the scope of the class to which it has been declared as friend.
 Since it is not in the scope of the class, it cannot be called using the object of that class.

64
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

 It can be invoked like a normal function without the help of any object.
 Unlike member functions, it cannot access the member names directly and has to use an object
name and dot membership operator with each member name, (e.g., A.x).
 It can be declared either in the public or the private part of a class without affecting its meaning.
 Usually, it has the objects as arguments.

Q. What do you understand by operator overloading? How does it differ from operator overriding?
Ans:
Overloading an operator means attaching additional meaning and semantics to an operator. It
enables an operator to exhibit more than one operation polymorphically.
For example, the normal function of the addition operator (+) is essentially a numeric operator that
involves two number operands and evaluates to a numeric value to the sum of the two operands.
This function of the addition operator can be extended to evaluate string concatenation.
e.g., “COM” + “PUTER” should produce a single string “COMPUTER”.

This redefining the effect of an operator, keeping the original meaning and action intact, is called
operator overloading.
The general syntax of operator overloading is:
<return_type> operator <operator_being_overloaded> (<argument list>);

where ‘operator’ is the keyword and is preceded by the ‘return_type’ of the function.

To overload the addition operator (+) to concatenate two characters, the following declaration,
which could be either member or friend function, would be needed:
char * operator +(char *s2);

Q. What is an overloading function? How compiler decide which function to used? Explain with
example.
Ans:

We overload a function name f by declaring more than one function with the name f in the
same scope. The declarations of f must differ from each other by the types and/or the
number of arguments in the argument list. When we call an overloaded function named f,
the correct function is selected by comparing the argument list of the function call with the
parameter list of each of the overloaded candidate functions with the name f. A candidate
function is a function that can be called based on the context of the call of the overloaded
function name.

Let us consider a function print, which displays an int. As shown in the following
example, we can overload the function print to display other types, for example, double
and char*. We can have three functions with the same name, each performing a similar
operation on a different data type:

#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}

65
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void print(char* c) {
cout << " Here is char* " << c << endl;
}

int main()
{
print(10);
print(10.10);
print("ten");
}

The following is the output of the above example:

Here is int 10
Here is float 10.1
Here is char* ten

Here the compiler calls the function depending on the parameter, passed through the function. That
means, if we pass a double value through the function print(), then the compiler will execute the
definition with the double argument. So, the function void print(double f) will execute.

Q. Comment on the statement: 'A member function that has polymorphic behavior must be declared
virtual'.
Ans:
If a member function has a polymorphic behavior then it must has same name and different
definition. Now with in a class hierarchy a particular class can get both the function with same
signature and different definition from different upper hierarchy classes. Then with in that class the
polymorphic function will create some complexity. Now if the polymorphic function is declared as
virtual in the upper hierarchy class, then the different definition of that function will not come to the
child class and the problem corresponding to the different definition will resolved.

66
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Q. Give an example of pure virtual function.


Ans:
A pure virtual function is a virtual function that we want to force derived classes to override. If a
class has any unoverridden pure virtuals, it is an "abstract class" and we can't create objects of that
type.
Classes containing pure virtual methods are termed "abstract;" they cannot be instantiated directly,
and a subclass of an abstract class can only be instantiated directly if all inherited pure virtual
methods have been implemented by that class or a parent class. Pure virtual methods typically have
a declaration (signature) and no definition (implementation).

Example of a pure virtual function

#include<iostream.h>
class base
{
private:
int x, y;
public:
virtual void getdata() = 0;
virtual void display() = 0;
};

class derivedB : public base


{
Data Members
Member Functions
};

Generally, a virtual function is public; if private, it has to be accessed by a public member function
as follows:

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

class Base
{ virtual void show(){cout<<"\nshow base";} //private member
public:
void display(){cout<<"\ndisplay base";}
void getShow(){show();}
};

class Derived:public Base


{
public:
void display(){cout<<"\ndisplay derived";}
void show(){cout<<"\nshow derived";}
};
int main()
{
clrscr();
Base B, *bptr;
Derived D;

67
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

cout<<"\nbptr points to base...........\n";


bptr=&B;
bptr->display();
bptr->getShow();

cout<<"\n\nbptr points to derived......\n";


bptr=&D;
bptr->display();
bptr->getShow();
return 0;
}

Q. What is late binding?


Ans:
Late Binding is run-time resolution, also known as ‘dynamic loading’ or ‘dynamic binding’. 'Late'
refers to the fact that the binding decisions (which binary to load, which function to call) is deferred
as long as possible, often until just before the function is called, rather than having the binding
decisions made at compile time (early).
In some programs, it is not possible to know which function will be called until runtime (when the
program is run). This is known as late binding (or dynamic binding). In C++, one way to get late
binding is to use function pointers (a function pointer is a type of pointer that points to a function
instead of a variable).
Run-time dynamic linking enables the process to continue running even if a DLL is not available.
The process can then use an alternate method to accomplish its objective. For example, if a process
is unable to locate one DLL, it can try to use another, or it can notify the user of an error.
The function that a function pointer points to can be called by using the function call operator (())
on the pointer.

For example, the following code calls the Add() function:

int Add(int nX, int nY)


{
return nX + nY;
}

int main()
{
//Create a function pointer and make it point to the Add function
int (*pFcn)(int, int) = Add;
cout << pFcn(5, 3) << endl; //add 5 + 3

return 0;
}

Late binding is slightly less efficient since it involves an extra level of indirection. With early
binding, the compiler can tell the CPU to jump directly to the function’s address. Whereas, with late
binding, the program has to read the address held in the pointer and then jump to that address. This
involves one extra step, making it slightly slower. However, the advantage of late binding is that it
is more flexible than early binding, because decisions about what function to call do not need to be
made until run time.

68
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

TOPIC : FILE OPERATION

--------------------------------------
Short Answer Questions
--------------------------------------

Q. Write & explain the output of the following code :

#include<iostream.h>
void main()
{
double amt = 100.00;
cout << sizeof (amt) – sizeof (double) << endl;
}

Ans:

The program will generate the output 0.


Explanation :
Sizeof() is an operator which will take the data type as input and return the memory space (in byte),
taken by that datatype. Here sizeof(amt) is 8 and the sizeof(double) is also 8. So, the value of the
whole expression will be 0.

Q. Why is that all functions of “ostream” class can operate on “fstream” class?
Ans:
“fstream” class is a file class derived from ‘iostream’ and is used for both reading and writing
operations. Hence, the functions of “ostream” class (used for writing operations) can operate on
“fstream” class.

Q. Differentiate between getline() and getc() functions.


Ans:

getline() getc()
This is a member function of istream This is a function from the header file stdio.h
The return type of the function is istream& The return type of the function is either ascii value of
read character on success and EOF on error.
It deals with a whole line. It deals with only a character.
Syntax : Syntax : int getc(file * stream)
istream& getline(unsigned char *,int,char=’\n’)

Q. Why do you use random access files?


Ans:
Random access file is used in a situation when it is required to move directly to a specific location
in the file instead of moving through it sequentially. For example, in order to modify a value in
record number 29, random access file technique is very useful which will place the file pointer at
the beginning of the record 29, instead of sequentially going through each record.

Q. Why is the file iomanip.h included?


Ans:
The file “iomanip.h” should be included while using manipulators with parameters in a program.
Manipulators are functions specifically designed to be used in conjunction with the insertion (<<)

69
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

and extraction (>>) operators on stream objects to provide a specific format to the output. Some
manipulators, viz., setw, setprecision etc., take parameters. Using such manipulators in the program
explicitly need to include file “iomanip.h” as the “iomanip.h” file contains information useful for
performing formatted I/O with parameterized stream manipulators.

Q. What do you mean by header file?


Ans:
A header file or include file is a file, usually in the form of source code, is automatically included in
another source file by the compiler. Typically, header files are included via compiler directives at
the beginning (or head) of the other source file. A header file commonly contains forward
declarations of classes, subroutines, variables, and other identifiers. Identifiers that need to be
declared in more than one source file can be placed in one header file, which is then included
whenever its contents are required.

Q. Define binary file.


Ans:
A binary file is a file of any length that holds bytes with values in the range 0 to 0xff. (0 to 255).
These bytes have no other meaning. In a text file a value of 10 means line feed, 26 means end of
file, and so on. Software reading or writing text files has to deal with line ends.
Nowadays, we can call a binary file a stream of bytes and more modern languages tend to work
with streams rather than files. The important part is the data rather than where it came from.
In binary file, we do not need to format any data, and data may not use the separation codes used by
text files to separate elements (like space, newline, etc.).

--------------------------------------
Long Answer Questions
--------------------------------------

Q. Explain different file handling operations in C++.

Ans:
C++ provides the following classes to perform output and input of characters to/from files:

ofstream : Stream class to write on files


ifstream : Stream class to read from files
fstream : Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream and ostream. cin is an
object of class ‘istream’ and cout is an object of class ‘ostream’. The classes ‘istream’ and
‘ostream’ define two member functions get() and put() respectively to handle the single character
input/output operations.
The get() function is of two types, viz., get(char*) that assigns the input character to its
argument and the get(void) that returns the input character. These functions are to be invoked using
appropriate object.
For example,

char c;
cin.get(c); //get a character from keyboard and assign it to c
while (c! = ‘\n’)
{
cout << c; //display the character on screen
//get another character
}

Similarly, the function put() can be used to output a line of text, character by
character.

70
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

For example,
cout << put(‘x’); // displays the character x.

cout << put(68); //displays the character D.

We can use file streams the same way we use cin and cout, with the only difference that we have to
associate these streams with physical files.
Below given is an example:

//Basic File Operations


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ofstream myfile;
myfile.open ("example.txt");
myfile<<"Writing this to a file.\n";
myfile.close();
return 0;
}

The above set of codes creates a file called example.txt and inserts a sentence into it in the same
way as we do with cout, but using the file stream myfile instead. The output for the above program
[file example.txt] is:

Open a file

The first operation generally performed on an object of one of these classes is to associate it to a
real file. This procedure is known as to ‘open a file’. An open file is represented within a program
by a stream object (an instantiation of one of these classes, say, ‘myfile’ in the previous example)
and any input or output operation performed on this stream object will be applied to the physical file
associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);

where ‘filename’ is a null-terminated character sequence of type const char * (the same
type that string literals have) representing the name of the file to be opened, and ‘mode’ is an
optional parameter with a combination of the following flags:

ios::in  Open for input operations.


ios::out  Open for output operations.
ios::binary  Open in binary mode.
ios::ate  Set the initial position at the end of the file. If this flag is not set to any value, the initial
position is the beginning of the file.
ios::app  All output operations are performed at the end of the file, appending the content to the
current
content of the file. This flag can only be used in streams open for output-only operations.
ios::trunc  If the file opened for output operations already existed before, its previous content is
deleted
and replaced by the new one.

71
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open
the file example.bin in binary mode to add data we could do it by the following call to member
function open() :

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Each one of the open() member functions of the classes ofstream, ifstream and fstream has a default
mode that is used if the file is opened without a second argument:

class default mode parameter


ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed,
even if a mode that does not include them is passed as second argument to the open() member
function. Note that the default value is only applied if the function is called without specifying any
value for the mode parameter. If the function is called with any value in that parameter the default
mode is overridden, not combined.

File streams opened in binary mode, perform input and output operations independently of any
format considerations. Non-binary files are known as text files, and some translations may occur
due to formatting of some special characters (like newline and carriage return characters).

Reading a file
We can read and display a line of text more efficiently using the line-oriented input/output functions
getline() and writer(). The getline() function reads a whole line of text that end with a newline
character. This function can be invoked by using the object ‘cin’ as follows:
cin.getline(line, size);

This function will read character input into the variable ‘line’. The reading is terminated as soon as
either the newline character ‘\n’ is encountered or number of characters (size) are read.
It is important to note that ‘cin’ can read strings without any white space, i.e., just one word
and not a sentence.

Closing a file
When we are finished with our input and output operations on a file we shall close it so that its
resources become available again. In order to do that we have to call the stream's member function
close(), i.e., myfile.close();

This member function takes no parameters, flushes the associated buffers and close the file.

Once this member function is called, the stream object can be used to open another file, and the file
is available again to be opened by other processes. In case that an object is destructed while still
associated with an open file, the destructor automatically calls the member function close().

Q. What is the difference between header files and library files?


Ans:
A header file contains declaration of something (constants, classes, ...), usually ends with a .h or hpp
extension.

A DLL (dynamically linked library) is a binary file (with .dll, .ocx, .a, ... extentions), containing
functions, resources, ... and can be linked to your program at run-time. In order to use a DLL you
need to include the corresponding header file, which declares things in the DLL, so that your

72
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

program gets compiled. The DLL file is automatically loaded (by system) at run-time when your
executable program invokes functions and asks for resources.

A library file (also called static library, with .lib extension usually) is a binary file which also
contains functions and variables like DLL, but resolved at compile-time, meaning they need to be
provided at link-time.

Dynamic and static libraries are often provided together with header file (but no source file, which
contains the implementation) when the provider lets you use his/her functions/services but doesnt
give you access to the implementation.

16. Explain salient features of the file handling operations in C++.


Ans:

C++ provides the following classes to perform output and input of characters to/from files:

ofstream:Stream class to write on files


ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream.

Open a file
The first operation generally performed on an object of one of these classes is to associate it
to a real file. This procedure is known as to open a file. An open file is represented within a
program by a stream object (an instantiation of one of these classes, in the previous
example this was myfile) and any input or output operation performed on this stream object
will be applied to the physical file associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);

Closing a file
When we are finished with our input and output operations on a file we shall close it so that
its resources become available again. In order to do that we have to call the stream's
member function close(). This member function takes no parameters, and what it does is to
flush the associated buffers and close the file:
myfile.close();

Checking state flags


In addition to eof(), which checks if the end of file has been reached, other member
functions exist to check the state of a stream (all of them return a bool value):

bad()
Returns true if a reading or writing operation fails. For example in the case that we try to
write to a file that is not open for writing or if the device where we try to write has no space
left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like
when an alphabetical character is extracted when we are trying to read an integer number.

73
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the
previous functions would return true.
In order to reset the state flags checked by any of these member functions we have just seen
we can use the member function clear(), which takes no parameters.

tellg() and tellp()


These two member functions have no parameters and return a value of the member type
pos_type, which is an integer data type representing the current position of the get stream
pointer (in the case of tellg) or the put stream pointer (in the case of tellp).

seekg() and seekp()


These functions allow us to change the position of the get and put stream pointers. Both
functions are overloaded with two different prototypes. The first prototype is:
seekg ( position );
seekp ( position );

Q. Write a short note on opening a file with open() member function.


Ans:

void open ( const char * filename,


ios_base::openmode mode = ios_base::in | ios_base::out );

Open file

Opens a file whose name is s, associating its content with the stream object to perform
input/output operations on it. The operations allowed and some operating details depend on
parameter mode.

The function effectively calls rdbuf()->open(filename,mode).

If the object already has a file associated (open), the function fails.

On failure, the failbit flag is set (which can be checked with member fail), and depending
on the value set with exceptions an exception may be thrown.

// fstream::open
#include <fstream>
using namespace std;

int main () {

fstream filestr;

filestr.open ("test.txt", fstream::in | fstream::out | fstream::app);

// >>i/o operations should go here... <<

filestr.close();

return 0;
}

Q. How will you define an output stream?

74
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

Ans:
An output stream implements stream buffer output, or output operations. The following classes are
derived from ostream:
 ofstream
 ostream_withassign
 ostrstream
 iostream

The iostream class combines istream and ostream to implement input and output to stream buffers.

iostream

ios base ios ostream ofstream

ostringstream

ostream objects are stream objects used to write and format output as sequences of characters.
Specific members are provided to perform these output operations, which can be divided in two
main groups:

Formatted output
These member functions interpret and format the data to be written as sequences of characters.
These type of operation is performed using member and global functions that overload the insertion
operator (operator<<).

Unformatted output
Most of the other member functions of the ostream class are used to perform unformatted output
operations, i.e. output operations that write the data as it is, with no formatting adaptations. These
member functions can write a determined number of characters to the output character sequence
(put, write) and manipulate the put pointer (seekp, tellp).

TOPIC : DATA STRUCTURE ( MSCIT 105)

--------------------------------------
Short Answer Questions
--------------------------------------

Q. What is a stack?
Ans:
Stack is an ordered list in which there are only one end, for both insertions and deletions. Elements
are inserted and deleted from the same end called “TOP” of the stack. Stack is called Last In First
Out (LIFO) list, as the first element in the stack will be the last element out of the stack. It implies
that the elements are removed from a stack in the reverse order of that in which they were inserted
into the stack.

Following are the some basic operations associated with stacks:


Push: Insertion of any element is called the “Push” operation.
Pop: Deletion from the stack is called the “Pop” operation. The “most” and “least” accessible
elements in a stack are known as the “Top” and “Bottom” of the stack respectively.

A common example of a stack phenomenon, which permits the selection of only its end element, is
a pile of trays in a cafeteria. Plates can be added to or removed from this pile only from the top.

Q. Give a binary tree representation.


Ans:

75
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

A tree is a type of data structure that can be used to store information. Unlike ‘stacks’ and ‘queues’,
which are linear data structures, trees are ‘hierarchical’ data structures. The structure of a tree is
‘hierarchical’ means that things are ordered ‘above’ or ‘below’ other things.

The element at the top of the tree is called the ‘root’. The elements that are directly under an
element are called its ‘children’. The element directly above something is called its ‘parent’.
Finally, elements with no children are called ‘leaves’.

For example:

tree
----
j <-- root
/ \
f k
/ \ \
a h z <-- leaves

In the above given example, a is a child of f and f is the parent of a.

Despite the hierarchical order of the structure of the tree, the order enforced on objects in the tree
will depend on how we use the tree. It implies that unlike a stack whose operations are usually
limited to push and pop, there are many different kinds of trees and ways to use them.

Q. What is function overriding?


Ans:
In C++, Function Overridding involves a relationship between a super class method and subclass
method. Here, subclass method replaces the superclass. Overridding blocks inheritence. Function
overriding must have same signature. Method overriding is the ability of the inherited class
rewriting the virtual method of the base class, i.e., redefining a function in a class is function
overriding. Overridding is runtime polymorphism.

Let A and B be two classes. Here A is the base and B is the child class, publicly inherited. A has a
function fun() with in it’s public part.
class A
{
int i;
public:
void fun( )
{
cout<<”Hello World”;
}
}

class B : public A
{
public:
int j;
}
Now, B can access the function fun( ), as a public member. But if class B want to change the
definition of the function fun( ), then B has to redefine the function fun( ) with in it, as:
class B : public A
{
public:
int j;

76
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

void fun( )
{
cout<<”Hello Colorful World”;
}
}
Then the function definition with in the child class, B will work. And the definition of class A will
be deactivated. –This phenomenon is called Function Overriding.

TOPIC : MACRO, TEMPLATE, EXCEPTION HANDLING

--------------------------------------
Short Answer Questions
--------------------------------------

Q. What is a macro in C++?


Ans:

A macro in computer science is a rule or pattern that specifies how a certain input sequence
(often a sequence of characters) should be mapped to an output sequence (also often a
sequence of characters) according to a defined procedure. The mapping process which
instantiates a macro into a specific output sequence is known as macro expansion.
In general Macro is of two types :
i) Macro Name
ii) Function Like Macro
Example :
#define <macro-name> <char-sequence…>
#define PI 3.141592 //named macro
#define funmac(a) (a<=0 ? –a : a) //function like macro

Q. Differentiate between macros and functions.


Ans:

Macro Function
1. A macro repeats a process, this process 1. A function is something that is used in
can be clicking and typing, therefore programming languages, say, VB. Thus, functions
reduces the working time. are the parts of the scripts that tell it to do most of
the work, thereby, takes much work time.

2. A macro just replaces the code 2. A function doesn't replace code but it performs
assigned to it. For example, if a macro what it is supposed to do, i.e., whatever is
"PI" is defined with a value 3.14, the mentioned in the set of code. For example,
compiler just replaces PI with 3.14
wherever it finds PI in the program. void swap(int &a, int &b)
{ int t = a;
a = b;
b = t;
}

The above function call swap(m, n) will exchange


the values of m and n using their aliases (reference
variables) a and b.
3. In a case, where there is a overhead 3. If the macro definition go like kind of x++ and y+

77
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

and takes more CPU cycles to execute +, it's better to use functions and avoid macros.
the same, it is better to use a macro that
needs just simple substitution.

Q. What are the advantages of template function in C++?


Ans:

In C++, the advantages of template function are as follows:


 A function template can be used to define a generic function that is type-inspecific. In other
words, when we define the function, we do not specify what types are passed to it, or what
types are returned from it, provided if we are seeking the output with the default type that
uses the function.
 We may define types for any parameters or return values that are type-specific, such as, a
generic comparison function that returns a Boolean value of ‘true’ or ‘false’.
 We can define a function, for example, that takes one or more parameters, and only specify
their presence, not the types that should be associated with them.

A generic example is as follows:

template <class T>


T Maximum ( T one, T two )
{
if( one > two )
return one;
return two;
}

In the above example, in the first line, it has been notified to the compiler that this is a template, and
that one should be able to specialize it with a single type, defined by the placeholder, T. This could,
in fact, be any value, where T is just a common convention.
Q. Distinguish between the terms fatal error and nonfatal error.
Ans:

Fatal Error Non-Fatal Error


1. The term “fatal error” denotes a kind 1. The term "non-fatal" error is a kind of error
of error that causes the program to crash which when encountered, the compiler does
as soon as it is encountered. not stop there.
2. For example, if a fatal error is 2. On facing a non-fatal error, the compiler
encountered in the line 3 of a 50 lines goes on and reports all the 'non-fatal' errors
program, only the fatal error will be that it encounters all at once.
displayed showing that the program has
just one error, even if there are 20 more
errors in the program from line 3 to line
50. This is because, as soon as the
compiler encounters the fatal error on
line 3, it stops and does not find further
errors. If a fatal error is found and solved,
the compiler does not stop and goes on
and finds the other errors and reports
them on the next build.

--------------------------------------
Long Answer Questions

78
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

--------------------------------------

Q. Explain exception handling.


Ans:
An ‘exception’ is a situation in which a program has an unexpected circumstance that the section of
code containing the problem is not explicitly designed to handle. In C++, exception handling is
useful because it makes it easy to separate the error handling code from the code written to handle
the chores of the program. Thus it makes reading and writing the code easier. When errors occur,
the function generating the error can 'throw' an exception.

For example, let us take an example containing a function that does division:

const int DivideByZero = 10;


//....
double divide(double x, double y)
{
if(y==0)
{
throw DivideByZero;
}
return x/y;
}

The function will throw DivideByZero as an exception that can then be caught by an exception-
handling catch statement that catches exceptions of type int. The necessary construction for
catching exceptions is a try catch system. If we wish to have our program check for exceptions, we
must enclose the code that may have exceptions thrown in a try block. For example:
try
{
divide(10, 0);
}
catch(int i)
{
if(i = = DivideByZero)
{
cerr<<"Divide by zero error";
}
}

The catch statement catches exceptions that are of the proper type. For example, we can throw
objects of a class to differentiate between several different exceptions. As well, once a catch
statement is executed, the program continues to run from the end of the catch.

Q. List five common examples of exceptions (in C++).


Ans :

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

Exception Description
1) bad_alloc thrown by new on allocation failure
thrown by dynamic_cast when fails with a
2) bad_cast
referenced type
3) bad_exception thrown when an exception type doesn't match any

79
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304

catch
4) bad_typeid thrown by typeid
5) ios_base::failure thrown by functions in the iostream library

For example, if we use the operator new and the memory cannot be allocated, an exception of type
bad_alloc is thrown :
try
{
int *myarray = new int[1000];
}
catch(bad_alloc&)
{
cout<< "Error allocating memory."<< endl;
}

80

You might also like