C Interview Questions
C Interview Questions
Enlisted below are the most popular C++ programming interview questions that are answered by a C+
+ expert.
Basic C++
The first line that begins with “#” is a preprocessor directive. In this case, we are using include as a
directive which tells the compiler to include a header while “iostream.h” which will be used for basic
input/output later in the program.
Next line is the “main” function that returns an Integer. The main function is the starting point of
execution for any C++ program. Irrespective of its position in the source code file, the contents of the
main function are always executed first by the C++ compiler.
In the next line, we can see open curly braces that indicate the start of a block of a code. After this,
we see the programming instruction or the line of code that uses the count which is the standard
output stream (its definition is present in iostream.h).
This output stream takes a string of characters and prints it to a standard output device. In this case it
is, “Hello, World!”. Please note that each C++ instruction ends with a semicolon (;), which is very
much necessary and omitting it will result in compilation errors.
Before closing the braces}, we see another line “return 0;”. This is the returning point to the main
function.
Every C++ program will have a basic structure as shown above with a preprocessor directive, main
function declaration followed by a block of code and then a returning point to the main function which
indicates successful execution of the program.
1
Q #2) What are the Comments in C++?
Answer: Comments in C++ are simply a piece of source code ignored by the compiler. They are only
helpful for a programmer to add a description or additional information about their source code.
/* block comment */
The first type will discard everything after the compiler encounters “//”. In the second type, the
compiler discards everything between “/*” and “*/”.
Example:
1 int Result;
2 char c;
3 int a,b,c;
All the above are valid declarations. Also, note that as a result of the declaration, the value of the
variable is undetermined.
C = ‘A’;
2
Q #4) Comment on Local and Global scope of a variable.
Answer: The scope of a variable is defined as the extent of the program code within which the
variable remains active i.e. it can be declared, defined or worked with.
2. Global Scope: A variable has a global scope when it is accessible throughout the program. A
global variable is declared on top of the program before all the function definitions.
Example:
1 #include <iostream.h>
2 Int globalResult=0; //global variable
3 int main()
4{
5 Int localVar = 10; //local variable.
6 …..
7
8}
Q #5) What is the precedence when there is a Global variable and a Local variable in the
program with the same name?
Answer: Whenever there is a local variable with the same name as that of a global variable, the
compiler gives precedence to the local variable.
Example:
1 #include <iostream.h>
2 int globalVar = 2;
3 int main()
4{
5 int globalVar = 5;
6 cout<<globalVar<<endl;
7}
The output of the above code is 5. This is because, although both the variables have the same name,
the compiler has given preference to the local scope.
3
Q #6) When there is a Global variable and Local variable with the same name, how will you
access the global variable?
Answer: When there are two variables with the same name but different scope, i.e. one is a local
variable and the other is a global variable, the compiler will give preference to a local variable. In
order to access the global variable, we make use of “scope resolution operator (::)”. Using this
operator, we can access the value of the global variable.
Example:
1 #include<iostream.h>
2 int x= 10;
3 int main()
4{
5 int x= 2;
6 cout<<”Global Variable x = “<<::x;
7 cout<<”\nlocal Variable x= “<<x;
8}
Output:
Global Variable x = 10
local Variable x= 2
Q #7) How many ways are there to initialize an int with a Constant?
Answer: There are two ways:
The first format uses traditional C notation.
int result = 10;
Constants
Q #8) What is a Constant? Explain with an example.
Answer: A constant is an expression that has a fixed value. They can be divided into integer,
decimal, floating point, character or string constants depending on their data type. Apart from
decimal, C++ also supports two more constants i.e. octal (to the base 8) and hexadecimal (to the
base 16) constants.
Examples of Constants:
75 //integer (decimal)
0113 //octal
0x4b //hexadecimal
3.142 //floating point
4
‘c’ //character constant
“Hello, World” //string constant
Note: When we have to represent a single character, we use single quotes and when we want to
define a constant with more than one character, we use double quotes.
Q #9) How do you define/declare constants in C++?
Answer: In C++, we can define our own constants using the #define preprocessor directive.
#define Identifier value
Example:
1 #include<iostream.h>
2 #define PI 3.142
3 int main ()
4{
5 float radius =5, area;
6 area = PI * r * r;
7 cout<<”Area of a Circle = “<<area;
8}
In the above examples, whenever the type of a constant is not specified, C++ compiler defaults it to
an integer type.
Operators
Q #10) Comment on Assignment Operator in C++.
Answer: Assignment operator in C++ is used to assign a value to another variable.
a = 5;
One property which C++ has over the other programming languages is that the assignment operator
can be used as the rvalue (or part of an rvalue) for another assignment.
Example:
a = 2 + (b = 5);
is equivalent to:
b = 5;
a = 2 + b;
Which means, first assign 5 to variable b and then assign to a, the value 2 plus the result of the
previous expression of b(that is 5), leaves a with a final value of 7.
Q #11) What is the difference between equal to (==) and Assignment Operator (=)?
Answer: In C++, equal to (==) and assignment operator (=) are two completely different operators.
Equal to (==) is equality relational operator that evaluates two expressions to see if they are equal
and returns true if they are equal and false if they are not.
The assignment operator (=) is used to assign a value to a variable. Hence, we can have a complex
assignment operation inside the equality relational operator for evaluation.
6
Let’s demonstrate the various arithmetic operators with the following piece of code.
Example:
1 #include <iostream.h>
2 int main ()
3{
4 int a=5, b=3;
5 cout<<”a + b = “<<a+b;
6 cout<”\na – b =”<<a-b;
7 cout<<”\na * b =”<<a*b;
8 cout<<”\na / b =”<<a/b;
9 cout<<”\na % b =“<<a%b;
10
11 return 0;
12 }
Output:
a+b=8
a – b =2
a * b =15
a / b =2
a % b=1
As shown above, all the other operations are straightforward and the same as actual arithmetic
operations, except the modulo operator which is quite different. Modulo operator divides a and b and
the result of the operation is the remainder of the division.
Example:
7
1 value += increase; is equivalent to value = value + increase;
2 if base_salary is a variable of type int.
3 int base_salary = 1000;
4 base_salary += 1000; #base_salary = base_salary + 1000
5 base_salary *= 5; #base_salary = base_salary * 5;
Q #14) State the difference between Pre and Post Increment/Decrement Operations.
Answer: C++ allows two operators i.e ++ (increment) and –(decrement), that allow to add 1 to the
existing value of a variable and subtract 1 from the variable respectively. These operators are in turn,
called increment (++) and decrement (–).
Example:
a=5;
a++;
The second statement, a++, will cause 1 to be added to the value of a. Thus a++ is equivalent to
a = a+1; or
a += 1;
A unique feature of these operators is that we can prefix or suffix these operators with the variable.
Hence, if a is a variable and we prefix the increment operator it will be
++a;
a++;
The difference between the meaning of pre and post depends upon how the expression is evaluated
and the result is stored.
Example:
8
a = 5; b=6;
++a; #a=6
b–; #b=6
–a; #a=5
b++; #6
1 int age;
2 cin>>age;
As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin (keyboard)
to enter the data. “cin” processes the input only when the RETURN key is pressed.
“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It directs the
data that followed it into the cout stream.
Example:
1 cout<<”Hello, World!”;
2 cout<<123;
Statement block under while is executed as long as the condition in the given expression is true.
Example:
1 #include <iostream.h>
2 int main()
3{
9
4 int n;
5 cout<<”Enter the number : “;
6 cin>>n;
7 while(n>0)
8 {
9 cout<<” “<<n;
10 --n;
11 }
12 cout<<”While loop complete”;
13 }
In the above code, the loop will directly exit if n is 0. Thus in while loop, the terminating condition is at
the beginning of the loop and if it's fulfilled, no iterations of the loop are executed.
Example:
1 #include<iostream.h>
2 int main()
3{
4 int n;
5 cout<<”Enter the number : “;
6 cin>>n;
7 do {
8 cout<<n<<”,”;
9 --n;
10 }while(n>0);
11 cout<<”do-while complete”;
12 }
In the above code, we can see that the statement inside the loop is executed at least once as the
loop condition is at the end. These are the main differences between the while and do-while.
In case of while, we can directly exit the loop at the beginning if the condition is not met whereas in
the do-while loop we execute the loop statements at least once.
10
Functions
Q #17) What do you mean by ‘void’ return type?
Answer: All functions should return a value as per the general syntax.
However, in case, if we don't want a function to return any value, we use “void” to indicate that. This
means that we use “void” to indicate that the function has no return value or it returns “void”.
Example:
1 void myfunc()
2{
3 Cout<<”Hello,This is my function!!”;
4}
5 int main()
6{
7 myfunc();
8 return 0;
9}
Hence, whatever modifications are made to the parameters in the called function are not passed back
to the calling function. Thus the variables in the calling function remain unchanged.
Example:
1 void printFunc(int a,int b,int c)
2{
11
3 a *=2;
4 b *=2;
5 c *=2;
6}
7
8 int main()
9
10 {
11
12 int x = 1,y=3,z=4;
13 printFunc(x,y,z);
14 cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
15 }
Output:
x=1
y=3
z=4
As seen above, although the parameters were changed in the called function, their values were not
reflected in the calling function as they were passed by value.
However, if we want to get the changed values from the function back to the calling function, then we
use “Pass by Reference” technique.
12
Output:
x=2
y=6
z=8
As shown above, the modifications done to the parameters in the called functions are passed to the
calling function when we use “Pass by reference” technique. This is because, using this technique we
do not pass a copy of the parameters but we actually pass the variable’s reference itself.
Q #19) What are Default Parameters? How are they evaluated in C++ function?
Answer: Default parameter is a value that is assigned to each parameter while declaring a function.
This value is used if that parameter is left blank while calling to the function. To specify a default value
for a particular parameter, we simply assign a value to the parameter in the function declaration.
If the value is not passed for this parameter during the function call, then the compiler uses the
default value provided. If a value is specified, then this default value is stepped on and the passed
value is used.
Example:
1 int multiply(int a, int b=2)
2{
3 int r;
4 r = a * b;
5 return r;
6}
7
8 int main()
9 {
10
11 Cout<<multiply(6);
12 Cout<<”\n”;
13 Cout<<multiply(2,3);
14 }
Output:
12
6
As shown in the above code, there are two calls to multiply function. In the first call, only one
parameter is passed with a value. In this case, the second parameter is the default value provided.
13
But in the second call, as both the parameter values are passed, the default value is overridden and
the passed value is used.
Arrays
Q #21) Why are arrays usually processed with for loop?
Answer: Array uses the index to traverse each of its elements.
If A is an array then each of its element is accessed as A[i]. Programmatically, all that is required for
this to work is an iterative block with a loop variable i that serves as an index (counter) incrementing
from 0 to [Link]-1.
This is exactly what a loop does and this is the reason why we process arrays using for loops.
Answer: The above code is syntactically correct and will compile fine.
The only problem is that it will just delete the first element of the array. Though the entire array is
deleted, only the destructor of the first element will be called and the memory for the first element is
released.
Q #24) What's the order in which the objects in an array are destructed?
Answer: Objects in an array are destructed in the reverse order of construction: First constructed,
last destructed.
In the following Example, the order for destructors will be a[9], a[8], …, a[1], a[0]:
1 voiduserCode()
2{
3 Car a[10];
4 ...
14
5}
Pointers
Q #25) What is wrong with this code?
T *p = 0;
delete p;
Answer: In the above code, the pointer is a null pointer. Hence naturally, the program will crash in an
attempt to delete the null pointer.
Example:
1 int a=10;
2 int& b = a;
Storage Classes
Q #27) What is a Storage Class? Mention the Storage Classes in C++.
Answer: Storage class determines the life or scope of symbols such as variable or functions.
C++ supports the following storage classes:
Auto
Static
Extern
Register
Mutable
1 void f()
15
2 {
3 int i;
4 auto int j;
5 }
1 void f()
2{
3 static int i;
4 ++i;
5 printf(“%d “,i);
6}
If a global variable is static, then its visibility is limited to the same source code.
In the above code, “i” can be visible outside the file where it is defined.
16
Q #33) When to use “const” reference arguments in a function?
Answer: Using “const” reference arguments in a function is beneficial in several ways:
“const” protects from programming errors that could alter data.
As a result of using “const”, the function is able to process both const and non-const actual
arguments, which is not possible when “const” is not used.
Using a const reference, allows the function to generate and use a temporary variable in an
appropriate manner.
Class: Class is a successor of the Structure. C++ extends the structure definition to include the
functions that operate on its members. By default all the members inside the class are private.
Object-Oriented Programming with C++
Classes, Constructors, Destructors
Q #36) What is Namespace?
Answer: Namespaces allow us to group a set of global classes, objects and/or functions under a
specific name.
Where identifier is any valid identifier and the namespace-body is the set of classes, objects, and
functions that are included within the namespace. Namespaces are especially useful in the case
where there is a possibility for more than one object to have the same name, resulting in name
clashes.
Example:
A::b(int, long) const is mangled as ‘b__C3Ail'.
For a constructor, the method name is left out.
Example:
Describe PRIVATE, PROTECTED and PUBLIC along with their differences and give examples.
1 class A{
2 int x; int y;
3 public int a;
4 protected bool flag;
public A() : x(0) , y(0) {} //default (no argument)
5
constructor
6 };
7
8 main(){
9
10 A MyObj;
11
18
12 MyObj.x = 5; // Compiler will issue a ERROR as x is private
13
int x = MyObj.x; // Compiler will issue a compile ERROR MyObj.x is
14
private
15
16 MyObj.a = 10; // no problem; a is public member
17 int col = MyObj.a; // no problem
18
[Link] = true; // Compiler will issue a ERROR; protected values are
19
read only
20 bool isFlag = [Link]; // no problem
Example:
1 class A{
2 int x; int y;
3 public A() : x(0) , y(0) {} //default (no argument) constructor
4 };
5 main()
6 {
A Myobj; // Implicit Constructor call. In order to
7
allocate memory on stack,
//the default constructor is implicitly
8
called.
A * pPoint = new A(); // Explicit Constructor call. In
9
order to allocate
//memory on HEAP we call
10
the default constructor.
19
11 }
Example:
1 class A{
2 int x; int y;
3 public int color;
4 public A() : x(0) , y(0) {} //default (no argument) constructor
5 public A( const A& ) ;
6 };
7 A::A( const A & p )
8{
9 this->x = p.x;
10 this->y = p.y;
11 this->color = [Link];
12 }
13 main()
14 {
15 A Myobj;
16 [Link] = 345;
17 A Anotherobj = A( Myobj ); // now Anotherobj has color = 345
18 }
Example:
1 class B {
2 public: B (int m = 0) : n (m) {} int n;
3 };
4 int main(int argc, char *argv[])
5{
6 B b; return 0;
20
7 }
Q #46) What is the role of Static keyword for a class member variable?
Answer: Static member variable shares a common memory across all the objects created for the
respective class. We need not refer to the static member variable using an object. However, it can be
accessed using the class name itself.
Q #48) What's the order in which the local objects are destructed?
Answer: Consider following a piece of code:
1 Class A{
2 ….
3 };
4 int main()
5 {
6 A a;
7 A b;
8 ...
9 }
In the main function, we have two objects created one after the other. They are created in an
order, first a then b. But when these objects are deleted or if they go out of the scope, the
destructor for each will be called in the reverse order in which they were constructed. Hence,
the destructor of b will be called first followed by a. Even if we have an array of objects, they
will be destructed in the same way in the reverse order of their creation.
Overloading
Q #49) Explain Function Overloading and Operator Overloading.
Answer: C++ supports OOPs concept Polymorphism which means “many forms”.
21
In C++ we have two types of polymorphism, i.e. Compile-time polymorphism, and Run-time
polymorphism. Compile time polymorphism is achieved by using an Overloading technique.
Overloading simply means giving additional meaning to an entity by keeping its base meaning intact.
Operator Overloading:
This is yet another type of compile-time polymorphism that is supported by C++. In operator
overloading, an operator is overloaded, so that it can operate on the user-defined types as well with
the operands of the standard data type. But while doing this, the standard definition of that operator is
kept intact.
For Example, Addition operator (+) that operates on numerical data types can be overloaded to
operate on two objects just like an object of complex number class.
Q #50) What is the difference between Method Overloading and Method Overriding in C++?
Answer: Method overloading is having functions with the same name but different argument list. This
is a form of compile-time polymorphism.
Method overriding comes into picture when we rewrite the method that is derived from a base class.
Method overriding is used while dealing with run-time polymorphism or virtual functions.
Q #51) What is the difference between a Copy Constructor and an Overloaded Assignment
Operator?
Answer: A copy constructor and an overloaded assignment operator basically serve the same
purpose i.e. assigning the content of one object to another. But still, there is a difference between the
two.
Example:
1 complex c1,c2;
2 c1=c2; //this is assignment
3 complex c3=c2; //copy constructor
22
Here, both c1 and c2 are already existing objects and the contents of c2 are assigned to the object
c1. Hence, for overloaded assignment statement both the objects need to be created already.
Next statement, complex c3 = c2 is an example of the copy constructor. Here, the contents of c2 are
assigned to a new object c3, which means the copy constructor creates a new object every time
when it executes.
Q #53) Function can be overloaded based on the parameter which is a value or a reference.
Explain if the statement is true.
Answer: False. Both, Passing by value and Passing by reference look identical to the caller.
Function overloading allows us to reduce the complexity of the code and make it more clear and
readable as we can have the same function names with different argument lists.
Inheritance
Q #55) What is Inheritance?
Answer: Inheritance is a process by which we can acquire the characteristics of an existing entity
and form a new entity by adding more features to it.
In terms of C++, inheritance is creating a new class by deriving it from an existing class so that this
new class has the properties of its parent class as well as its own.
For Example, a class driver will have two base classes namely, employee and a person because a
driver is an employee as well as a person. This is advantageous because the driver class can inherit
the properties of the employee as well as the person class.
But in the case of an employee and a person, the class will have some properties in common.
However, an ambiguous situation will arise as the driver class will not know the classes from which
the common properties should be inherited. This is the major disadvantage of multiple inheritance.
Q #59) Explain the ISA and HASA class relationships. How would you implement each?
Answer: “ISA” relationship usually exhibits inheritance as it implies that a class “ISA” specialized
version of another class. Example, An employee ISA person. That means an Employee class is
inherited from the Person class.
Contrary to “ISA”, “HASA” relationship depicts that an entity may have another entity as its member
or a class has another object embedded inside it.
So taking the same example of an Employee class, the way in which we associate the Salary class
with the employee is not by inheriting it but by including or containing the Salary object inside the
Employee class. “HASA” relationship is best exhibited by containment or aggregation.
Each class has its own constructors and destructors. The derived class also does not inherit the
assignment operator of the base class and friends of the class. The reason is that these entities are
specific to a particular class and if another class is derived or if it is the friend of that class, then they
cannot be passed onto them.
Polymorphism
Q #61) What is Polymorphism?
Answer: The basic idea behind polymorphism is in many forms. In C++, we have two types of
Polymorphism:
24
In compile time polymorphism, we achieve many forms by overloading. Hence, we have Operator
overloading and function overloading. (We have already covered this above)
This means, that an object reacts differently to the same function call. This type of polymorphism can
use virtual function mechanism.
Whenever we have functions with the same name in the base as well as derived class, there arises
an ambiguity when we try to access the child class object using a base class pointer. As we are using
a base class pointer, the function that is called is the base class function with the same name.
To correct this ambiguity we use the keyword “virtual” before the function prototype in the base class.
In other words, we make this polymorphic function Virtual. By using a Virtual function, we can remove
the ambiguity and we can access all the child class functions correctly using a base class pointer.
1 class SHAPE{
public virtual Draw() = 0; //abstract class with a pure
2
virtual method
3 };
25
4 class CIRCLE: public SHAPE{
5 public int r;
6 public Draw() { this->drawCircle(0,0,r); }
7 };
8 class SQUARE: public SHAPE{
9 public int a;
10 public Draw() { this->drawSquare(0,0,a,a); }
11 };
12
13 int main()
14 {
15 SHAPE shape1*;
16 SHAPE shape2*;
17
18 CIRCLE c1;
19 SQUARE s1;
20
21 shape1 = &c1;
22 shape2 = &s1;
23 cout<<shape1->Draw(0,0,2);
24 cout<<shape2->Draw(0,0,10,10);
25 }
In the above code, SHAPE class has a pure virtual function and is an abstract class (cannot be
instantiated). Each class is derived from SHAPE implementing Draw () function in its own way.
Further, each Draw function is virtual so that when we use a base class (SHAPE) pointer each time
with the object of the derived classes (Circle and SQUARE), then appropriate Draw functions are
called.
Example:
1 class Shape { public: virtual void draw() = 0; };
26
Base class that has a pure virtual function as its member can be termed as an “Abstract class”. This
class cannot be instantiated and it usually acts as a blueprint that has several sub-classes with further
implementation.
Example:
1 Class A{
2 ….
3 ~A();
4 };
5 Class B:publicA{
6 …
7 ~B();
8 };
9 B b;
10 A a = &b;
11 delete a;
As shown in the above example, when we say delete a, the destructor is called but it’s actually the
base class destructor. This gives rise to the ambiguity that all the memory held by b will not be
cleared properly.
What we do is, we make the base class constructor “Virtual” so that all the child class destructors also
become virtual and when we delete the object of the base class pointing to the object of the derived
class, the appropriate destructor is called and all the objects are properly deleted.
27
1 Class A{
2 ….
3 virtual ~A();
4 };
5 Class B:publicA{
6 …
7 ~B();
8 };
9 B b;
10 A a = &b;
11 delete a;
Friend
Q #66) What is a friend function?
Answer: C++ class does not allow its private and protected members to be accessed outside the
class. But this rule can be violated by making use of the “Friend” function.
As the name itself suggests, friend function is an external function which is a friend of the class. For
friend function to access the private and protected methods of the class, we should have a prototype
of the friend function with the keyword “friend” included inside the class.
When we have a requirement to access the internal implementation of a class (private member)
without exposing the details by making the public, we go for friend functions.
Advanced C++
28
Templates
Q #68) What is a template?
Answer: Templates allow creating functions that are independent of data type (generic) and can take
any data type as parameters and return value without having to overload the function with all the
possible data types. Templates nearly fulfill the functionality of a macro.
The only difference between both the prototypes is the use of keyword class or typename. Their basic
functionality of being generic remains the same.
Exception Handling
Q #69) What is Exception Handling? Does C++ support Exception Handling?
Answer: Yes C++ supports exception handling.
We cannot ensure that code will execute normally at all times. There can be certain situations which
might force the code written by us to malfunction, even though it’s error-free. This malfunctioning of
code is called Exception.
When an exception has occurred, the compiler has to throw it so that we know an exception has
occurred. When an exception has been thrown, the compiler has to ensure that it is handled properly,
so that the program flow continues or terminates properly. This is called handling of an exception.
Thus in C++, we have three keywords i.e. try, throw and catch which are in exception handling.
As shown above, the code that might potentially malfunction is put under the try block. When code
malfunctions, an exception is thrown. This exception is then caught under the catch block and is
handled i.e. appropriate action is taken.
29
Q #70) Comment on C++ standard exceptions?
Answer: C++ supports some standard exceptions that can be caught if we put the code inside the try
block. These exceptions are a part of the base class “std:: exception”. This class is defined in the
C++ header file <exception>.
Q #71) What is a Standard Template Library (STL)? What are the various types of STL
Containers?
Answer: A Standard Template Library (STL) is a library of container templates approved by the ANSI
committee for inclusion in the standard C++ specification. We have various types of STL containers
depending on how they store the elements.
1. Queue, Stack – These are the same as traditional queue and stack and are called adaptive
containers.
2. Set, Map – These are basically containers that have key/value pairs and are associative in nature.
3. Vector, deque – These are sequential in nature and have similarity to arrays.
Q #73) What is the difference between an External Iterator and an Internal Iterator? Describe
an advantage of the External Iterator.
Answer: An internal iterator is implemented with member functions of the class that has items to step
through.
An external iterator is implemented as a separate class that can be bound to the object that has items
to step through. The basic advantage of an External iterator is that it’s easy to implement as it is
implemented as a separate class.
Secondly, as it’s a different class, many iterator objects can be active simultaneously.
30