QUAN-C
QUAN-C
--------------------------------------
Short Answer Questions
--------------------------------------
Ans:
#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. Consider the following section of C++ program, in which a and b are int variables
b = 2;
a = 1;
a = b++;
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
struct employee
{
int empId;
…
}
then
struct data
{
employee e; //structure within structure
int age;
...
}
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:
The type of member function arguments must exactly match with the types declared in the class
definition of the <class_name>.
#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).
For example:
average = sum / float(i);
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;
}
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.
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(\).
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.
4
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
E.g.
struct
{ char name[35];
int roll;
float total_marks;
}student;
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.
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
Special care should be taken while naming a variable that is being shared by more than one file
containing C++ programs.
Among numerous keywords in C++, the four keywords are: class, integer, register, try.
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.
#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.
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.
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 (*).
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.
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.
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
Q. Consider the following section of C++ program, in which i and n are int variables
n = 7;
i = 4;
i = n++;
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:
9
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
Q. Find the values of x >> 2 and x & y using the following declaration:
unsigned char x = ‘\011’, y = ‘\027’;
Ans:
10
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
--------------------------------------
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
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
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:
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.
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.
‘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
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.
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.
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 :
15
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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.
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.
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”;
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++;
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-- ;
Whereas,
i = --n;
would decrement n to 4 and then set i to 4.
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 :
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
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.
#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;
}
}
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.
>>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 ;
}
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.
#include<iostream.h>
int main()
{
int a =0;
start:
cout<<“\n”<< ++a;
if (a<50)
goto start;
}
--------------------------------------
Long Answer Questions
--------------------------------------
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
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.
1. 'while' loop
2. 'do while' loop
3. 'for' loop
#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;
}
}
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);
}
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;
}
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.
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
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.
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
--------------------------------------
Short Answer Questions
--------------------------------------
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.
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.
29
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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.
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:
Now, another object can be created of abc type from ‘myabc1’, as shown below:
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:
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.
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.
31
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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.
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.
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:
32
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
...
--------------------------------------
Long Answer Questions
--------------------------------------
Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as below:
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.
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:
void main(void)
{
int *ptr, size;
cin>>size;
ptr = new int[size];
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.
The difference between object oriented program and structured program is as follows:
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.
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.
35
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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.
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 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.
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:
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.
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.
class Base
{
37
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
public:
int m_nPublic;
private:
int m_nPrivate;
};
Pub()
{
//The derived class always uses the immediate parent's class access
specifications
//Thus, Pub uses Base's access specifiers
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.
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.
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.
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.
class abc
{
int x,y;
public:
abc();
abc(int);
abc(int, int);
~abc()
{
cout << “Object being destroyed!!”;
}
}
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 print_i() {
cout << "Value of i = " << i << endl;
cout << "Again, value of i = " << this->i << endl;
}
};
int main()
{
X xobj;
xobj.set_i(11);
xobj.print_i();
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();
}
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.
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();
}
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"
TOPIC : INHERITANCE
--------------------------------------
Short Answer Questions
--------------------------------------
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
--------------------------------------
};
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.,
45
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
members of ABC
};
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.
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.
#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;
}
};
public:
void get1()
{
cout<<"\n\n1st test score <strong class="highlight">of</strong> "<<rno<<" is :";
cin>>score1;
}
};
public:
void get2()
{
cout<<"\n\n2nd test score <strong class="highlight">of</strong> "<<rno<<" is :";
cin>>score2;
}
};
public:
void result()
{
average=int((score1+score2)/2);
}
};
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;
}
}
In this case the variables and functions of the public part of class A will come to the public
part of class B.
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.
--------------------------------------
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().
(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.
51
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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 map objects in the problem domain to those objects in the program.
The data-centered design approach enables to capture more details of a model in implementable
form.
Message passing techniques for communication between objects makes the interface descriptions
with external systems much simpler.
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.
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.
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.
--------------------------------------
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>)
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:
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 error message will you receive when the function “void f(void) {return (1)}” is compiled?
Ans:
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.
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:
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
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
--------------------------------------
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
void main()
{ int i = 0;
char arrStr[2][30] = {“Brainware”,”PTU”}; //initialization
printf("%s", arrStr[0]);
printf("%s", arrStr[1]);
}
--------------------------------------
Long Answer Questions
--------------------------------------
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};
59
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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
--------------------------------------
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.
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;
}
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.
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”;
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
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.
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
};
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.
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");
}
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
#include<iostream.h>
class base
{
private:
int x, y;
public:
virtual void getdata() = 0;
virtual void display() = 0;
};
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();}
};
67
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
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
--------------------------------------
Short Answer Questions
--------------------------------------
#include<iostream.h>
void main()
{
double amt = 100.00;
cout << sizeof (amt) – sizeof (double) << endl;
}
Ans:
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.
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’)
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.
--------------------------------------
Long Answer Questions
--------------------------------------
Ans:
C++ provides the following classes to perform output and input of characters to/from 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.
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:
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():
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:
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:
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().
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.
C++ provides the following classes to perform output and input of characters to/from 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():
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();
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.
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.
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.close();
return 0;
}
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
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).
--------------------------------------
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.
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.
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
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.
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.
--------------------------------------
Short Answer Questions
--------------------------------------
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
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;
}
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.
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:
--------------------------------------
Long Answer Questions
78
C++ Programming : MSCIT 103 / MCA 202 / BSCIT 303 / BCA 304
--------------------------------------
For example, let us take an example containing a function that does division:
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.
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