Saturday, 7 July 2012

c++ Interview Q and Ans

Question and Answers

This chapter is meant to answer some of the questions that were not discussed in the earlier.

1Q.) What is the difference between structure and class?

First of all there is this common assumption that a structure can only contain data and cannot contain functions. Well, structures can contain member functions as well. Then there is the belief that structures do not have private and public areas. In fact structures also have private and public areas within them. The next assumption is that we cannot have constructors; but even that is possible in structures. You might be thinking that this isn’t true. Check out the example below:

struct counter
    int count;

counter( )

void input( )
cout<<endl<<"Enter the count : ";

void display( )
cout<<endl<<"The count is : "<<count;


int main( )
counter c1;
c1.display( );
c1.input( );
c1.display( );
return 0;

The output is:

The count is : 10
Enter the count : 3
The count is : 3

Can we have destructors? Yes, even that is possible in a structure. Well, so what is the difference between a structure and a class? The point to be noted is that structures were actually part of the C language. In C we did not have data encapsulation and neither did we have object oriented programming. But when C++ was developed the capability of structures was extended to such an extent that they were similar to classes. The only difference between a class and a C++ structure is that in a class by default everything is made private. In structures, by default, everything would be public. That’s the only difference between a C++ structure and a class (note the words: "C++ structure").

Since C++ tried to maintain compatibility with C, we usually never use a structure like a class (i.e. we retain a structure for its normal use, as it was used in C and that was to group data together – no private, no constructor etc). Thus when we use structures we'll only use it as if it were a C structure (to contain only data).

2Q.) If I were to make a declaration and definition as follows:

int i=4;

Now in which part of memory will the value of ‘i' be stored in? Will it be in the RAM?? And they say that when we use the ‘new’ operator, memory is taken from the ‘heap’…Is the heap made use of only when the ‘new’ operator is used or can a program make use of the heap in any other way? How does heap differ from stack?? Or are they the same? And what is free-store?

When you say memory, we always refer to the RAM. If you have done a course in microprocessor programming you will learnt about it. The stack is basically part of the RAM and whenever the program has to branch elsewhere, it will store the return address in the stack. There are many other uses for the stack as well. Now when a parent process asks the operating system to create a child process, the OS allocates space for the child process's code, stack, and data (variables, whose values are given in the program itself). These regions are just memory blocks. The orders in which these blocks exist and the amount of memory purely depends on the OS implementation. Hence a programmer should not be bothered about it. The 'stack' is used to allocate temporary variables. All local variables are temporary variables. All global variables are allocated in the 'data' region. So where did this term 'heap' come from? Heap is a region of memory which is used by 'malloc' (this is an operator similar to ‘new’ and was used in C) and 'new' to allocate memory. When the OS allocates memory, it usually doesn’t do so in a count of bytes. Usually the OS allocates memory to a process in terms of 4KB. Hence when a process needs 100 bytes, the OS gives it 4KB. The 'malloc' and 'new', consider this as the 'heap'. They allocate memory from the 'heap'. When the heap gets over, again the OS is requested for more memory. All this happens transparently; so it is hard to see it before your eyes. Actually this term 'heap' is kind of getting wiped away. It got introduced in MSDOS where the 'heap' referred to all the memory from the last block allocated to a process to the end of memory. This was so because, MSDOS was not a multitasking OS and it didn’t have any protection from user processes. So that was some background information. Coming back to the question, int i = 4; If the above declaration was done locally (i.e. within a function), then the allocation is done on the stack. If it is done globally it is in the 'data' section. There is another section called 'bss' which is the un-initialized data., which is similar to 'data'. There is one more point to note. Sometimes we have a region of memory called as ‘free store’. Sometimes this would be the same as the ‘heap’ but sometimes it could be different. If they are different then there are certain things you have to note. When you use the C++ dynamic memory operators (new and delete), these will operate on the free store. When you use the C operators (malloc and free) they will operate on the ‘heap’. What you have to take care of is not to mix up ‘new’ with ‘free’ and ‘malloc’ with ‘delete’. Suppose the ‘heap’ and ‘free store’ are different, then you will be allocating space in one region and freeing up memory elsewhere. So always use ‘new’ along with ‘delete’ or ‘malloc’ along with ‘free’. Well.. I also need to tell you this very very important thing. C Standards doesn’t document what I've explained to above. Though this is the convention that is generally followed by most of the C/C++ compilers, a programmer should never wonder where in memory his 'variable' is living. Rather he should think, 'what is the scope of a ‘variable'. That is better programming practice. Usage of global variables should be only after thorough review of the problem.

3Q.) By the way, who decides on the size of the stack???

This is again operating system dependent. Every operating system has a specific executable file format. Like in MSDOS you have EXE file format. The old executable format of Linux was 'a.out'. Now the native format is ELF(Executable and Loadable file format), for most of the Unixes. So at the time of compilation, the compiler computes the amount of stack you'd need and it puts in the respective fields of these executable files. Mind you, these executable files are not fully executable. They have a header part, which says where the 'code' section is, where the 'data' section is, how much stack is needed, how much memory to allocate, what are the regions that need not be loaded into memory and so on. As a rule, a C/C++ programmer when writing for a Standard implementation should not be bothered about setting the stack and such. These were a issue only in MSDOS. But still some compilers provide you non-standard features to control the size of the stack. Like the variable 'extern int _staklen' in Turbo C/C++. Supposing you set _staklen = 0x1000; then the compiler after compilation, when generating the EXE file, will write in the EXE header that you need a stack of '_staklen' bytes. When you execute the executable, the OS will read this header first to load your program. It'll see how much space you need and will allocate it. Then it'll load the respective sections of your program into the respective regions of memory. So, usually it is better not to bother about changing stack settings.

4Q.) I tried the following piece of code and got shocking results:

double a,b;
I get the result as a=0 and b=0. Why???

You have to be very careful while carrying out operations on floating point/double quantities. The problem is that the compiler when it encounters: 1/5 might assume it as integer division and hence the result will be 0. How to ensure that this doesn’t happen? Well, you have to specify the decimal point somewhere. For ex: 1/5.0 or 1.0/5 will give ‘a’ a value of 0.2 and now b will have the value as 2. Again be careful while doing floating point comparisons. Sometimes a decimal value cannot be stored exactly be the computer (because of limitations on the number of bits available) and hence the computer will store a value that is very close to what you expect. For ex: sometimes, 1.1 may be stored as a 1.099 or something of the sort. If you compare these two values for equality, the computer will say that both are not equal. So be careful while using floating point quantities.

5Q.) Can I call a function from within a function?

The main ( ) function does call other functions. Similarly you can call other functions also from within a function. See the example below: #include <iostream> using namespace std; void sum(int a, int b) { cout<<endl<<"The sum is : "<<a+b; } void input( ) { int x,y; cout<<endl<<"Enter the two numbers : "; cin>>x>>y; sum(x,y); } int main( ) { input( ); return 0; } The code will compile and run properly. You will get errors if you try to define a function within another function. The compiler will say that local function definitions are illegal. For instance in the above program you cannot define the function input ( ) within the main ( ) function.

6Q.) Assume that I am declaring a constant using #define (say something like PI). Does the #define act like a function? Will the #define take up memory space itself?

No, the #define's will not occupy any space in memory. They are called preprocessor directives. i.e they are processed before compilation. When you compile a program, there are different stages.. the first one is pre-processing where directives such as these can be expanded. So these are decided at compile time and not at run time.

Check out the following code:

#define X 100
int main( )
const int mark = 20;
int y,z;
y = X;
z = X + mark;
return 0;

In the above code, at the time of compilation all occurrences of 'X' will simply be replaced by '100'. But on the other hand when I define 'const int mark', it means that 'mark' is a variable whose value won’t change. So the compiler allocates some memory for the 'const int'. After preprocessing the code would look as below:

int main( )
const int mark = 20;
int y,z;
y = 100;
z = 100 + mark;
return 0;

7Q.) What is a library? Is it a collection of header files?

A library file contains functions, which can be called from your code. The header files usually declare these functions while their real implementation is present in the library files. Just have a look through stdio.h or conio.h., you'll find it contains tons of functions but their internal coding will not be there. The actual functions exist in the library, which is precompiled but not linked code. All these printf, scanf, gets, puts, etc. are in the library. You call them in every single program of yours. You can’t include the library just like that. You've to link your file with the library. If you are using Turbo C++, the compiler automatically does that for you (it might be a file called CS.LIB). But you can also do that manually. In some compilers you will have an option in your Project Settings to mention the library files that you want to link.
8Q.) Where should the ‘const’ keyword be placed? const int i=5; int const j=4; Which one is correct?

Both are acceptable. You can place the ‘const’ keyword before the data type or after the data type. But be careful about placing the ‘const’ keyword when you are using pointers. int x,y; int *const p1=&x; //constant pointer int const *p2; //not a constant pointer x=y=5; p2=&y; *p2=6; //Not allowed-you cannot modify the value at p2. p2=&x; //Allowed because p2 is not made a constant pointer The placement of the ‘const’ keyword will determine whether the pointer is a constant pointer or not.

9Q.) I get the following errors when attempting to compile my program (‘Time’ is a class that has private members called ‘hours’ and ‘minutes’):

'hours' cannot access private member declared in Class 'Time'
'minutes' cannot access private member declared in Class 'Time'

and, 'operator << is ambiguous'

These errors point to the line "ostream & operator<<(ostream & os, const Time & t)"
in my source code. The << operator has been overloaded using friend functions. Why can’t a friend function access the private members of the class? I am currently using Microsoft Visual C++.

A.) If you use some other compiler (other than VC++) you won’t have this problem. Actually this is a bug in Microsoft VC++ version 6.0. They have released a service pack to rectify this problem.

The problem (the bug) is because of ‘using namespace std;’ If you avoid this statement and use iostream.h you won’t have the problem. Another option is to define the overloaded operator << within your class itself (instead of defining it outside the class using the scope resolution operator).

Check out the following website for details about the problem as well as an explanation about the bug and the service pack.;EN-US;q192539

10Q.) What is name-mangling?

All C++ compilers make use of name mangling. When the compiler reads through the source code and encounters a function name, it stores the details about the function in a table (called a symbol table). For example if we have a function:

void sub (int, int);

the compiler will store this function in its symbol table. But functions in C++ are name mangled, i.e. the function name stored by the compiler is not the same one as given by us. The compiler may store it as:


Thus whenever the compiler encounters a function call to sub ( ) it will retrieve the appropriate definition for the function at compile-time. Name mangling permits C++ to implement function overloading. Let us say we have another function with the same name ‘sub’:

void sub (double,double);

The compiler will store this as


Thus whenever there is a statement calling the function sub ( ), the compiler will check the data types of the arguments and call the correct function.

C compilers do not implement name mangling and thus they do not support function-overloading. Different C++ compilers (supplied by different vendors) may implement name mangling in a different way but the bottom-line is that all C++ compilers implement name mangling.

Go back to the Contents Page 2

Copyright © 2004 Sethu Subramanian All rights reserved.
Yahoo! GeoCities
Yahoo! GeoCities

No comments:

Post a Comment

Write your openion about my blog spot..To get automatic facebook updates like my Page ..It takes only 1 min to write the comment and to like the page.. Thanks.