C++ Interview Questions

What is difference between C and C++ ?

  • C++ is Multi-Paradigm( not pure OOP, supports both procedural and object oriented) while C follows procedural style programming.
  • In C data security is less, but in C++ you can use modifiers for your class members to make it inaccessible from outside.
  • C follows top-down approach ( solution is created in step by step manner, like each step is processed into details as we proceed ) but C++ follows a bottom-up approach ( where base elements are established first and are linked to make complex solutions ).
  • C++ supports function overloading while C does not support it.
  • C++ allows use of functions in structures, but C does not permit that.
  • C++ supports reference variables( two variables can point to same memory location ). C does not support this.
  • C does not have a built in exception handling framework, though we can emulate it with other mechanism. C++ directly supports exception handling, which makes life of developer easy.

What is an Object/Instance?

Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below

Vehicle vehicleObject;

We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.

What do you mean by C++ access specifiers ?

[Questions regarding access specifiers are common not just in c++ interview but for other object oriented language interviews as well.]

Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected

  • private:
    Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.
  • public:
    Members declared as public are accessible from any where.
  • protected:
    Members declared as protected can not be accessed from outside the class except a child class. This access specifier has significance in the context of inheritance.

What is the use of volatile keyword in c++? Give an example.

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,

  1. int a = 10;
  2. while( a == 10){
  3. // Do something
  4. }

compiler may think that value of ‘a’ is not getting changed from the program and replace it with ‘while(true)’, which will result in an infinite loop. In actual scenario the value of ‘a’ may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.
In the above example if variable ‘a’ was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.

In how many ways we can initialize an int variable in C++?

In c++, variables can be initialized in two ways, the traditional C++ initialization using “=” operator and second using the constructor notation.

Traditional C++ initilization

  • int i = 10;

variable i will get initialized to 10.

Using C++ constructor notation

  • int i(10);

Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.

short a = 2000 + 20;

In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.

What is implicit conversion/coercion in c++?

Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.

short a = 2000 + 20;

In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.

What are C++ inline functions?

C++ inline functions are special functions, for which the compiler replaces the function call with body/definition of function. Inline functions makes the program execute faster than the normal functions, since the overhead involved in saving current state to stack on the function call is avoided. By giving developer the control of making a function as inline, he can further optimize the code based on application logic. But actually, it’s the compiler that decides whether to make a function inline or not regardless of it’s declaration. Compiler may choose to make a non inline function inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler may ignore. So, please note this point for the interview that, it is upto the compiler to make a function inline or not.

inline int min(int a, int b)

{

return (a < b)? a : b;

}

int main( )

{

cout << “min (20,10): ” << min(20,10) << endl;

cout << “min (0,200): ” << min(0,200) << endl;

cout << “min (100,1010): ” << min(100,1010) << endl;

return 0;

}

If the complier decides to make the function min as inline, then the above code will internally look as if it was written like

int main( )

{

cout << “min (20,10): ” << ((20 < 10)? 20 : 10) << endl;

cout << “min (0,200): ” << ((0 < 200)? 0 : 200) << endl;

cout << “min (100,1010): ” << ((100 < 1010)? 100 : 1010) << endl;

return 0;

}

What do you mean by translation unit in c++?

We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. In other words, a translation unit consists of

  • Contents of source file
  • Plus contents of files included directly or indirectly
  • Minus source code lines ignored by any conditional pre processing directives ( the lines ignored by #ifdef,#ifndef etc)

What do you mean by internal linking and external linking in c++?

A symbol is said to be linked internally when it can be accessed only from with-in the scope of a single translation unit. By external linking a symbol can be accessed from other translation units as well. This linkage can be controlled by using static and extern keywords.

What do you mean by storage classes?

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.

What is realloc() and free()? What is difference between them?

  • void* realloc (void* ptr, size_t size)

This function is used to change the size of memory object pointed by address ptr to the size given by size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour may occur depending the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do not match a pointer returned by an malloc(), calloc() or realloc().

  • void free (void* ptr)

This function is used to deallocate a block of memory that was allocated using malloc(), calloc() or realloc(). If ptr is null, this function does not doe anything.

What is difference between shallow copy and deep copy? Which is default?

[This question can be expected in any interviews, not just c++ interviews. This is a usual question in most of the java interviews.]

When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.

What do you mean by persistent and non persistent objects?

Persistent objects are the ones which we can be serialized and written to disk, or any other stream. So before stopping your application, you can serialize the object and on restart you can deserialize it. [ Drawing applications usually use serializations.]
Objects that can not be serialized are called non persistent objects. [ Usually database objects are not serialized because connection and session will not be existing when you restart the application. ]

Is it possible to get the source code back from binary file?

Technically it is possible to generate the source code from binary. It is called reverse engineering. There are lot of reverse engineering tools available. But, in actual case most of them will not re generate the exact source code back because many information will be lost due to compiler optimization and other interpretations.

What do you mean by pure virtual functions in C++? Give an example?

Pure virtual function is a function which doesn’t have an implementation and the same needs to be implemented by the the next immediate non-abstract class. (A class will become an abstract class if there is at-least a single pure virtual function and thus pure virtual functions are used to create interfaces in c++).

How to create a pure virtual function?

A function is made as pure virtual function by the using a specific signature, ” = 0″ appended to the function declaration as given below,

class SymmetricShape

{

public:

// draw() is a pure virtual function.

virtual void draw() = 0;

};

Why pure virtual functions are used if they don’t have implementation / When does a pure virtual function become useful?

Pure virtual functions are used when it doesn’t make sense to provide definition of a virtual function in the base class or a proper definition does not exists in the context of base class. Consider the above example, class SymmetricShape is used as base class for shapes with symmetric structure(Circle, square, equilateral triangle etc). In this case, there exists no proper definition for function draw() in the base class SymmetricShape instead the child classes of SymmetricShape (Cirlce, Square etc) can implement this method and draw proper shape.

What is virtual destructors? Why they are used?

[This c++ interview question is in a way related to polymorphism.]

Virtual destructors are used for the same purpose as virtual functions. When you remove an object of subclass, which is referenced by a parent class pointer, only destructor of base class will get executed. But if the destructor is defined using virtual keyword, both the destructors [ of parent and sub class ] will get invoked.

What is meant by reference variable in C++?

In C++, reference variable allows you create an alias (second name) for an already existing variable. A reference variable can be used to access (read/write) the original data. That means, both the variable and reference variable are attached to same memory location. In effect, if you change the value of a variable using reference variable, both will get changed (because both are attached to same memory location).

Is there a difference between class and struct?

The only difference between a class and struct are the access modifiers. Struct members are public by default; class members are private. It is good practice to use classes when you need an object that has methods and structs when you have a simple data object.

What is a class?

[Probably this would be the first question for a Java/c++ technical interview for freshers and sometimes for experienced as well. Try to give examples when you answer this question.]

Class defines a datatype, it’s type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.

class Vehicle

{

public:

int numberOfTyres;

double engineCapacity;

void drive(){

// code to drive the car

}

};

What are the basics concepts of OOPS?

  • Classes and Objects

Refer Questions 2 and 3 for the concepts about classes and objects

  • Encapsulation

Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It’s also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data. Consider the below class

class Person

{

private:

int age;

public:

int getAge(){

return age;

}

int setAge(int value){

if(value > 0){

age = value;

}

}

};

In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.

  • Data abstraction

Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.

class Stack

{

public:

virtual void push(int)=0;

virtual int pop()=0;

};

class MyStack : public Stack

{

private:

int arrayToHoldData[]; //Holds the data from stack

public:

void push(int) {

// implement push operation using array

}

int pop()

{

// implement pop operation using array

}

};

In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.

  • Inheritance

Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.

class SymmetricShape

{

public:

int getSize()

{

return size;

}

void setSize(int w)

{

size = w;

}

protected:

int size;

};

// Derived class

class Square: public SymmetricShape

{

public:

int getArea()

{

return (size * size);

}

};

In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.

What is the use of volatile keyword in c++? Give an example?

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,

  1. int a = 10;
  2. while( a == 10){
  3. // Do something
  4. }

compiler may think that value of ‘a’ is not getting changed from the program and replace it with ‘while(true)’, which will result in an infinite loop. In actual scenario the value of ‘a’ may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.
In the above example if variable ‘a’ was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.

How many storage classes are available in C++?

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.
Following storage classes are available in C++

  • auto

It’s the default storage class for local variables. They can be accessed only from with in the declaration scope. auto variables are allocated at the beginning of enclosing block and deallocated at the end of enclosing block.

void changeValue(void)

{

auto int i = 1 ;

i++;

printf ( “%d “, i ) ;

}

int main()

{

changeValue();

changeValue();

changeValue();

changeValue();

return 0;

}

Output:-

  1. 2 2 2 2

In the above example, every time the method changeValue is invoked, memory is allocated for i and de allocated at the end of the method. So it’s output will be same.

  • register

It’s similar to auto variables. Difference is that register variables might be stored on the processor register instead of RAM, that means the maximum size of register variable should be the size of CPU register ( like 16bit, 32bit or 64bit). This is normally used for frequently accessed variables like counters, to improve performance. But note that, declaring a variable as register does not mean that they will be stored in the register. It depends on the hardware and implementation.

int main()

{

register int i;

int array[10] = {0,1,2,3,4,5,6,7,8,9};

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

{

printf(“%d “, array[i]);

}

return 0;

}

Output:-

0 1 2 3 4 5 6 7 8 9

The variable i might be stored on the CPU register and due to which the access of i in the loop will be faster.

  • static

A static variable will be kept in existence till the end of the program unlike creating and destroying each time they move into and out of the scope. This helps to maintain their value even if control goes out of the scope. When static is used with global variables, they will have internal linkage, that means it cannot be accessed by other source files. When static is used in case of a class member, it will be shared by all the objects of a class instead of creating separate copies for each object.

void changeValue(void)

{

static int i = 1 ;

i++;

printf ( “%d “, i ) ;

}

int main(){

changeValue();

changeValue();

changeValue();

changeValue();

return 0;

}

Output:-

  1. 2 3 4 5

Since static variable will be kept in existence till the end of program, variable i will retain it’s value across the method invocations.

  • extern

extern is used to tell compiler that the symbol is defined in another translation unit (or in a way, source files) and not in the current one. Which means the symbol is linked externally. extern symbols have static storage duration, that is accessible through out the life of program. Since no storage is allocated for extern variable as part of declaration, they cannot be initialized while declaring.

int x = 10;

int main( )

{

extern int y ;

printf(“x: %d “, x );

printf(“y: %d”, y);

return 0;

}

int y = 70 ;

Output:-

x: 10 y: 70

extern variable is like global variable, it’s scope is through out the program. It can be defined anywhere in the c++ program.

  • mutable

mutable storage class can be used only on non static non const data a member of a class. Mutable data member of a class can be modified even is it’s part of an object which is declared as const.

class Test

{

public:

Test(): x(1), y(1) {};

mutable int x;

int y;

};

int main()

{

const Test object;

x = 123;

//object.y = 123;

/*

* The above line if uncommented, will create compilation error.

*/

cout<< “X:”<< object.x << “, Y:” << object.y;

return 0;

}

Output:-

X:123, Y:1

In the above example, we are able to change the value of member variable x though it’s part of an object which is declared as const. This is because the variable x is declared as mutable. But if you try to modify the value of member variable y, compiler will throw error.
You can find the summary of c++ storage class specifiers below

C++ Storage Specifier Storage Location Scope Of Variable Life Time
auto Memory (RAM) Local With in function
static Memory (RAM) Local Life time is from when the flow reaches the first declaration to the termination of program.
register CPU register Local With in function
extern Memory (RAM) Global Till the end of main program

What is ‘Copy Constructor’ and when it is called?

This is a frequent c++ interview question. Copy constructor is a special constructor of a class which is used to create copy of an object. Compiler will give a default copy constructor if you don’t define one. This implicit constructor will copy all the members of source object to target object.
Implicit copy constructors are not recommended, because if the source object contains pointers they will be copied to target object, and it may cause heap corruption when both the objects with pointers referring to the same location does an update to the memory location. In this case its better to define a custom copy constructor and do a deep copy of the object.

class SampleClass{

public:

int* ptr;

SampleClass();

// Copy constructor declaration

SampleClass(SampleClass &obj);

};

SampleClass::SampleClass(){

ptr = new int();

*ptr = 5;

}

// Copy constructor definition

SampleClass::SampleClass(SampleClass &obj){

//create a new object for the pointer

ptr = new int();

// Now manually assign the value

*ptr = *(obj.ptr);

cout<<“Copy constructor…\n”;

}

What are virtual functions and what is its use?

Virtual functions are member functions of class which is declared using keyword ‘virtual’. When a base class type reference is initialized using object of sub class type and an overridden method which is declared as virtual is invoked using the base reference, the method in child class object will get invoked.

class Base

{

int a;

public:

Base()

{

a = 1;

}

virtual void method()

{

cout << a;

}

};

class Child: public Base

{

int b;

public:

Child()

{

b = 2;

}

virtual void method()

{

cout << b;}

};

int main()

{

Base *pBase;

Child oChild;

pBase = &oChild;

pBase->method();

return 0;

}

In the above example even though the method in invoked on Base class reference, method of the child will get invoked since its declared as virtual.

What you mean by early binding and late binding? How it is related to dynamic binding?

[This c++ interview question is related to question about virtual functions ]

Binding is the process of linking actual address of functions or identifiers to their reference. This happens mainly two times.

  • During compilation : This is called early binding

For all the direct function references compiler will replace the reference with actual address of the method.

  • At runtime : This is called late binding.

In case of virtual function calls using a Base reference, as in shown in the example of question no: 2, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at runtime.
Dynamic binding is another name for late binding.

How to create a reference variable in C++?

Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.

  1. int a = 20;
  2. int& b = a;

The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a
Take a look at the below example to see how reference variables work.

  1. int main ()
  2. {
  3. int   a;
  4. int&  b = a;
  5. a = 10;
  6. cout << “Value of a : ” << a << endl;
  7. cout << “Value of a reference (b) : ” << b  << endl;
  8. b = 20;
  9. cout << “Value of a : ” << a << endl;
  10. cout << “Value of a reference (b) : ” << b  << endl;
  11. return 0;
  12. }

Above code creates following output.

Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20

What are the difference between reference variables and pointers in C++?

[This question is usually asked in a twisted way during c++ interviews. Sometimes the interviewer might use examples and ask you to find the error.]

Pointers Reference Variables
Pointers can be assigned to NULL References cannot be assigned NULL. It should always be associated with actual memory, not NULL.
Pointers can be (re)pointed to any object, at any time, any number of times during the execution. Reference variables should be initialized with an object when they are created and they cannot be reinitialized to refer to another object
Pointer has own memory address and location on stack Reference variables has location on stack, but shares the same memory location with the object it refer to.

What will the line of code below print out and why?

cout << 25u – 50;

The answer is not -25. Rather, the answer (which will surprise many) is 4294967271, assuming 32 bit integers. Why?

In C++, if the types of two operands differ from one another, then the operand with the “lower type” will be promoted to the type of the “higher type” operand, using the following type hierarchy (listed here from highest type to lowest type): long double, double, float, unsigned long int, long int, unsigned int, int (lowest).

So when the two operands are, as in our example, 25u (unsigned int) and 50 (int), the 50 is promoted to also being an unsigned integer (i.e., 50u).

Moreover, the result of the operation will be of the type of the operands. Therefore, the result of 25u – 50u will itself be an unsigned integer as well. So the result of -25 converts to 4294967271 when promoted to being an unsigned integer.

C++ supports multiple inheritance. What is the “diamond problem” that can occur with multiple inheritance? Give an example.

Let’s consider a simple example. A university has people who are affiliated with it. Some are students, some are faculty members, some are administrators, and so on. So a simple inheritance scheme might have different types of people in different roles, all of whom inherit from one common “Person” class. The Person class could define an abstract getRole() method which would then be overridden by its subclasses to return the correct role type.

But now what happens if we want to model a the role of a Teaching Assistant (TA)? Typically, a TA is both a grad student and a faculty member. This yields the classic diamond problem of multiple inheritance and the resulting ambiguity regarding the TA’s getRole() method:

Which getRole() implementation should the TA inherit? That of the Faculty Member or that of the Grad Student? The simple answer might be to have the TA class override the getRole() method and return newly-defined role called “TA”. But that answer is also imperfect as it would hide the fact that a TA is, in fact, both a faculty member and a grad student.

What is the error in the code below and how should it be corrected?

my_struct_t *bar;

/* … do stuff, including setting bar to point to a defined my_struct_t object … */

memset(bar, 0, sizeof(bar));

The last argument to memset should be sizeof(*bar), not sizeof(bar). sizeof(bar) calculates the size of bar (i.e., the pointer itself) rather than the size of the structure pointed to by bar.

The code can therefore be corrected by using sizeof(*bar) as the last argument in the call to memset.

A sharp candidate might point out that using *bar will cause a dereferencing error if bar has not been assigned. Therefore an even safer solution would be to use sizeof(my_struct_t). However, an even sharper candidate must know that in this case using *bar is absolutely safe within the call to sizeof, even if bar has not been initialized yet, since sizeof is a compile time construct.

What will i and j equal after the code below is executed? Explain your answer?

int i = 5;

int j = i++;

After the above code executes, i will equal 6, but j will equal 5.

Understanding the reason for this is fundamental to understanding how the unary increment (++) and decrement (–) operators work in C++.

When these operators precede a variable, the value of the variable is modified first and then the modified value is used. For example, if we modified the above code snippet to instead say int j = ++i;, i would be incremented to 6 and then j would be set to that modified value, so both would end up being equal to 6.

However, when these operators follow a variable, the unmodified value of the variable is used and then it is incremented or decremented. That’s why, in the statement int j = i++; in the above code snippet, j is first set to the unmodified value of i (i.e., 5) and then i is incremented to 6.

What is the problem in the code below? What would be an alternate way of implementing this that would avoid the problem?

size_t sz = buf->size();

while ( –sz >= 0 )

{

/* do something */

}

The problem in the above code is that –sz >= 0 will always be true so you’ll never exit the while loop (so you’ll probably end up corrupting memory or causing some sort of memory violation or having some other program failure, depending on what you’re doing inside the loop).

The reasons that –sz >= 0 will always be true is that the type of sz is size_t. size_t is really just an alias to one of the fundamental unsigned integer types. Therefore, since sz is unsigned, it can never be less than zero (so the condition can never be true).

One example of an alternative implementation that would avoid this problem would be to instead use a for loop as follows:

for (size_t i = 0; i < sz; i++)

{

/* do something */

}

Consider the two code snippets below for printing a vector. Is there any advantage of one vs. the other? Explain?

Option 1:

vector vec;

/* … .. … */

for (auto itr = vec.begin(); itr != vec.end(); itr++) {

itr->print();

}

Option 2:

vector vec;

/* … .. … */

for (auto itr = vec.begin(); itr != vec.end(); ++itr) {

itr->print();

}

Although both options will accomplish precisely the same thing, the second option is better from a performance standpoint. This is because the post-increment operator (i.e., itr++) is more expensive than pre-increment operator (i.e., ++itr). The underlying implementation of the post-increment operator makes a copy of the element before incrementing it and then returns the copy.

Implement a template function IsDerivedFrom() that takes class C and class P as template parameters. It should return true when class C is derived from class P and false otherwise?

This question tests understanding of C++ templates. An experienced developer will know that this is already a part of the C++11 std library (std::is_base_of) or part of the boost library for C++ (boost::is_base_of). Even an interviewee with only passing knowledge should write something similar to this, mostly likely involving a helper class:

template<typename D, typename B>

class IsDerivedFromHelper

{

class No { };

class Yes { No no[3]; };

 

static Yes Test( B* );

static No Test( … );

public:

enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };

 

};

 

 

template <class C, class P>

bool IsDerivedFrom() {

return IsDerivedFromHelper<C, P>::Is;

}

Implement a template boolean IsSameClass() that takes class A and B as template parameters. It should compare class A and B and return false when they are different classes and true if they are the same class?

template <typename T, typename U>

struct is_same

{

static const bool value = false;

};

 

template <typename T>

struct is_same<T, T>

{

static const bool value = true;

};

template <class A, class B>

bool IsSameClass() {

return is_same<A, B>::value;

}

Is it possible to have a recursive inline function?

Although you can call an inline function from within itself, the compiler will not generate inline code since the compiler cannot determine the depth of recursion at compile time.

What is the output of the following code?

#include <iostream>

class A {

public:

A() {}

~A() {

throw 42;

}

};

int main(int argc, const char * argv[]) {

try {

A a;

throw 32;

} catch(int a) {

std::cout << a;

}

}

This program will terminate abnormally. throw 32 will start unwinding the stack and destroy class A. The class A destructor will throw another exception during the exception handling, which will cause program to crash. This question is testing if developer has experience working with exceptions.

 

You are given library class Something as follows?

class Something {

public:

Something() {

topSecretValue = 42;

}

public:

bool somePublicBool;

int somePublicInt;

std::string somePublicString;

private:

int topSecretValue;

};

Implement a method to get topSecretValue for any given Something* object. The method should be cross-platform compatible and not depend on sizeof (int, bool, string)?

Create another class which has all the members of Something in the same order, but has additional public method which returns the value. Your replica Something class should look like:

class SomethingReplica {

public:

int getTopSecretValue() { return topSecretValue; }

public:

bool somePublicBool;

int somePublicInt;

std::string somePublicString;

private:

int topSecretValue;

};

Then, to get the value:

int main(int argc, const char * argv[]) {

Something a;

SomethingReplica* b = reinterpret_cast<SomethingReplica*>(&a);

std::cout << b->getTopSecretValue();

}

It’s important to avoid code like this in a final product, but it’s nevertheless a good technique when dealing with legacy code, as it can be used to extract intermediate calculation values from a library class. (Note: If it turns out that the alignment of the external library is mismatched to your code, you can resolve this using #pragma pack.)

Implement a void function F that takes pointers to two arrays of integers (A and B) and a size N as parameters. It then populates B where B`{`i`}` is the product of all A`{`j`}` where j != i?

For example: if A = {2, 1, 5, 9}, then B would be {45, 90, 18, 10}

This problem seems easy at first glance so a careless developer might write something like this:

void F(int* A, int* B, int N) {

int m = 1;

for (int i = 0; i < N; ++i) {

m *= A[i];

}

 

for (int i = 0; i < N; ++i) {

B[i] = m / A[i];

}

}

This will work for the given example, but when you add a 0 into input array A, the program will crash because of division by zero. The correct answer should take that edge case into account and look like this:

void F(int* A, int* B, int N) {

int m = 1;

int numZero = 0;

int zeroIndex = -1;

for (int i = 0; i < N; ++i) {

B[i] = 0;

if (A[i] == 0) {

++numZero;

zeroIndex = i;

} else {

m *= A[i];

}

}

if (numZero == 0) {

for (int i = 0; i < N; ++i) {

B[i] = m / A[i];

}

return;

}

if (numZero >= 2) {

return;

}

B[zeroIndex] = m;

}

The presented solution above has a Big O complexity of O(n). While there are simpler solutions available (ones that would ignore the need to take 0 into account), that simplicity has a price of complexity, generally running significantly slower.

When you should use virtual inheritance?

While it’s ideal to avoid virtual inheritance altogether (you should know how your class is going to be used) having a solid understanding of how virtual inheritance works is still important:

So when you have a class (class A) which inherits from 2 parents (B and C), both of which share a parent (class D), as demonstrated below:

#include <iostream>

class D {

public:

void foo() {

std::cout << “Foooooo” << std::endl;

}

};

class C:  public D {

};

class B:  public D {

};

class A: public B, public C {

};

int main(int argc, const char * argv[]) {

A a;

a.foo();

}

If you don’t use virtual inheritance in this case, you will get two copies of D in class A: one from B and one from C. To fix this you need to change the declarations of classes C and B to be virtual, as follows:

class C:  virtual public D {

};

 

class B:  virtual public D {

};

What is the output of the following code?

#include <iostream>

 

int main(int argc, const char * argv[]) {

int a[] = {1, 2, 3, 4, 5, 6};

std::cout << (1 + 3)[a] – a[0] + (a + 1)[2];

}

The above will output 8, since:

(1+3)[a] is the same as a[1+3] == 5

a[0] == 1

(a + 1)[2] is the same as a[3] == 4

This question is testing pointer arithmetic knowledge, and the magic behind square brackets with pointers.

While some might argue that this isn’t a valuable question as it appears to only test the capability of reading C constructs, it’s still important for a candidate to be able to work through it mentally; it’s not an answer they’re expected to know off the top of their head, but one where they talk about what conclusion they reach and how.

What is the output of the following code?

#include

class Base {

virtual void method() {std::cout << “from Base” << std::endl;}

public:

virtual ~Base() {method();}

void baseMethod() {method();}

};

class A : public Base

{

void method() {std::cout << “from A” << std::endl;}

public:

~A() {method();}

};

int main(void) {

Base* base = new A;

base->baseMethod();

delete base;

return 0;

}

The above will output:

from A

from A

from Base

The important thing to note here is the order of destruction of classes and how Base’s method reverts back to its own implementation once A has been destroyed.

Explain the volatile and mutable keywords?

The volatile keyword informs the compiler that a variable will be used by multiple threads. Variables that are declared as volatile will not be cached by the compiler to ensure the most up-to-date value is held.

The mutable keyword can be used for class member variables. Mutable variables are allowed to change from within const member functions of the class.

How many times will this loop execute? Explain your answer?

unsigned char half_limit = 150;

 

for (unsigned char i = 0; i < 2 * half_limit; ++i)

{

// do something;

}

If you said 300, you would have been correct if i had been declared as an int. However, since i was declared as an unsigned char, the corrct answer is that this code will result in an infinite loop.

Here’s why:

The expression 2 * half_limit will get promoted to an int (based on C++ conversion rules) and will have a value of 300. However, since i is an unsigned char, it is rerepsented by an 8-bit value which, after reaching 255, will overflow (so it will go back to 0) and the loop will therefore go on forever.

Explain abstraction?

– Simplified view of an object in user’s language is called abstraction.
– It is the simplest, well-defined interface to an object in OO and C++ that provides all the expected features and services to the user in a safe and predictable manner.
– It provides all the information that the user requires.
– Good domain knowledge is important for effective abstraction.
– It separates specifications from implementation & keeps the code simpler and more stable..

What is the real purpose of class – to export data?

No, the real purpose of a class is not to export data. Rather, it is to provide services. Class provides a way to abstract behaviour rather than just encapsulating the bits.

What things would you remember while making an interface?

-A class’s interface should be sensible enough. It should behave the way user expects it to.
– It should be designed from the outside in.

Explain the benefits of proper inheritance?

The biggest benefits of proper inheritance are :
1. Substitutability
2. Extensibility.

1. Substitutability :
The objects of a properly derived class can be easily and safely substituted for an object of its base class.

2. Extensibility :
The properly derived class can be freely and safely used in place of its base class even if the properly derived class is created a lot later than defining the user code. Extending the functionalities of a system is much easier when you add a properly derived class containing enhanced functionalities.

Does improper inheritance have a potential to wreck a project?

– Many projects meet a dead end because of bad inheritance. So, it certainly has the potential to wreck a project.
– Small projects still have a scope to avoid the complete consequence of bad inheritance if the developers communicate and co-ordinate with an easy system design. This kind of a luxury is not possible in big projects, which means that the code breaks in a way difficult and at times impossible way to fix it.

How should runtime errors be handled in C++?

– The runtime errors in C++ can be handled using exceptions.
– This exception handling mechanism in C++ is developed to handle the errors in software made up of independently developed components operating in one process and under synchronous control.
– According to C++, any routine that does not fulfil its promise throws an exception. The caller who knows the way to handle these exceptions can catch it.

When should a function throw an exception?

– A function should throw an exception when it is not able to fulfil its promise.
– As soon as the function detects a problem that prevents it from fulfilling its promise, it should throw an exception.
– If the function is able to handle the problem, recover itself and deliver the promise, then the exception should not be thrown.
– If an event happens very frequently then exception handling is not the best way to deal with it. It requires proper fixation.

Where are setjmp and longjmp used in C++?

-Setjmp and longjmp should not be used in C++.
– Longjmp jumps out of the function without unwinding the stack. This means that the local objects generated are not destructed properly.
– The better option is to use try/catch/throw instead. They properly destruct the local objects.

Are there any special rules about inlining?

Yes, there are a few rules about inlining :
1. Any source files that used the inline function must contain the function’s definition.
2. An inline function must be defined everywhere. The easier way to deal with this to define the function once in the class header file and include the definition as required. The harder way is to redefine the function everywhere and learn the one-definition rule.
3. Main() can not be inline.

Explain One-Definition Rule (ODR).

– According to one-definition rule, C++ constructs must be identically defined in every compilation unit they are used in.
– As per ODR, two definitions contained in different source files are called to be identically defined if they token-for-token identical. The tokens should have same meaning in both source files.
– Identically defined doesn’t mean character-by-character equivalence. Two definitions can have different whitespace or comments and yet be identical.

What are the advantages of using friend classes?

– Friend classes are useful when a class wants to hide features from users which are needed only by another, tightly coupled class.
– Implementation details can be kept safe by providing friend status to a tightly cohesive class.

What is the use of default constructor?

– It is a constructor that does not accept any parameters.
– If there is no user-defined constructor for a class, the compiler declares a default parameterless constructor called default constructor.
– It is an inline public member of its class.
– When the compiler uses this constructor to create an object – the constructor will have no constructor initializer and a null body.

Explain container class?

-Class to hold objects in memory or external storage. It acts as a generic holder.
– It has a predefined behaviour and a known interface.
– It is used to hide the topology used for maintaining the list of objects in memory.
– The container class can be of two types:
1. Heterogeneous container : Here the container class contains a group of mixed objects
2. Homogeneous container : Here the container contains all the same objects.

What is namespace?

– Namespaces are used to group entities like classes, objects and functions under a name.

Explain explicit container?

– These are constructors that cannot take part in an implicit conversion.
– These are conversion constructors declared with explicit keyword.
– Explicit container is reserved explicitly for construction. It is not used by the compiler to implement an implied conversion of types.

Explain class invariant?

– It is a condition that ensures correct working of a class and defines all the valid states for an object.
– When an object is created class invariants must hold.
– It is necessary for them to be preserved under all operations of the class.
– All class invariants are both preconditions as well as post-conditions for all operations or member functions of the class.

Differentiate between late binding and early binding. What are the advantages of early binding?

– Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time.
– Late binding occurs through virtual functions while early binding takes place when all the information needed to call a function is known at the time of compiling.
– Early binding increases the efficiency. Some of the examples of early binding are normal function calls, overloaded function calls, and overloaded operators etc.

Explain public, protected, private in C++?

These are three access specifiers in C++.
1. Public : Here the data members and functions are accessible outside the class.
2. Protected : Data members and functions are available to derived classes only.
3. Private : Data members and functions are not accessible outside the class.

Explain Copy Constructor?

It is a constructor which initializes it’s object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it.

When do you call copy constructors?

Copy constructors are called in these situations :
1. When compiler generates a temporary object.
2. When a function returns an object of that class by value .
3. When the object of that class is passed by value as an argument to a function .
4. When you construct an object based on another object of the same class.

Name the implicit member functions of a class?

1. default constructor
2. copy constructor
3. assignment operator
4. default destructor
5. address operator

Explain storage qualifiers in C++?

1. Const : This variable means that if the memory is initialised once, it should not be altered by a program.
2. Volatile : This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
3. Mutable : This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class or class member function is constant.

Explain dangling pointer?

– When the address of an object is used after its lifetime is over, dangling pointer comes into existence.
– Some examples of such situations are : Returning the addresses of the automatic variables from a function or using the address of the memory block after it is freed.

In what situations do you have to use initialization list rather than assignment in constructors?

– When you want to use non-static const data members and reference data members you should use initialization list to initialize them.

When does a class need a virtual destructor?

– If your class has at least one virtual function, you should have a virtual destructor. This allows you to delete a dynamic object through a baller to a base class object. In absence of this, the wrong destructor will be invoked during deletion of the dynamic object.

What is the type of “this” pointer? When does it get created?

– It is a constant pointer type. It gets created when a non-static member function of a class is called.

How would you differentiate between a pre and post increment operators while overloading?

– Mentioning the keyword int as the second parameter in the post increment form of the operator++() helps distinguish between the two forms.

What is a pdb file?

– A program database (PDB) file contains debugging and project state information that allows incremental linking of a Debug configuration of the program. This file is created when you compile a C/C++ program with /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug.

You run a shell on UNIX system. How would you tell which shell are you running?

– To check this you can simply do the Echo $RANDOM.
– The results will be :
1. Undefined variable if you are from the C-Shell,
2. A return prompts if you are from the Bourne shell,
3. A 5 digit random number if you are from the Korn shell. You could also do a ps -l and look for the shell with the highest PID.

What are Stacks? Give an example where they are useful?

A Stack is a linear structure in which insertions and deletions are always made at one end i.e the top – this is termed as Last in First out (LIFO). Stacks are useful when we need to check some syntax errors like missing parentheses.

Differentiate between an external iterator and an internal iterator? What is the advantage of an external iterator?

An external iterator is implemented as a separate class that can be “attach” to the object that has items to step through while an internal iterator is implemented with member functions of the class that has items to step through. With an external iterator many different iterators can be active simultaneously on the same object – this is its basic advantage.

Do you think the following code is fine? If not, what is the problem?

T *p = 0;
delete p;

– No, the code has a problem. The program will crash in an attempt to delete a null pointer.

In a function declaration, what does extern mean?

– Here, the extern tells the compiler about the existence of a variable or a function, even though the compiler hasn’t yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

You want to link a C++ program to C functions. How would you do it?

This can be done by using the extern “C” linkage specification around the C function declarations.

Explain STL?

STL stands for Standard Template Library. It is a library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.

What are the different types of STL containers?

Following are the 3 types of STL containers :
1. Adaptive containers : For e.g. queue, stack
2. Associative containers : For e.g. set, map
3. Sequence containers : For e.g. vector, deque

Explain Stack unwinding?

Stack unwinding is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.

How would you find out if a linked-list is a cycle or not?

We can find out if the linked-list is not a cycle by using two pointers. One of them goes 2 nodes every time while the second one goes at 1 node each time. If there is a cycle, the one that goes 2 nodes each time will meet the one that goes slower. If this happens, you can say that the linked-list is a cycle else not.

How does code-bloating occur in C++?

– Improper use of Inline functions and templates may lead to code bloating.
– Multiple Inheritance may also lead to code bloating.

Differentiate between realloc() and free()?

– Free() : A block of memory previously allocated by the malloc subroutine is freed by free subroutine. Undefined results come out if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will take place.

– Realloc() : This subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must be created with the malloc, calloc or realloc subroutines and should not be deallocated with the free or realloc subroutines. Undefined results show up if the Pointer parameter is not a valid pointer.

Explain Function overloading and Operator overloading?

a. Function overloading :
– The capability of C++ to define several functions of the same name with different sets of parameters is called function overloading. While calling an overloaded function, the C++ compiler selects the proper function by examining the number, types and order of the arguments.
– Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

b. Operator overloading :
– When the existing C++ operators are redefined to work on objects of user-defined classes, it is called operator overloading.
– Overloaded operators form a pleasant facade which improves the understandability and reduces maintenance costs without adding anything fundamental to the language.

Explain ``const`` reference arguments in function?

– It protects you against programming errors that can alter data.
– It allows function to process both const and non-const actual arguments.
– A function without const in the prototype can only accept non constant arguments.
– Using a const reference allows the function to generate and use a temporary variable appropriately.

Why do you use the namespace feature?

– Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries.
– The namespace feature surrounds a library’s external declaration with a unique namespace that eliminates the potential for those collisions.
– It identifies and assigns a name to a declarative region.
– The identifier in a namespace declaration must be unique in the declarative region in which it is used.
– The identifier is the name of the namespace and is used to reference its members.

Explain Overriding?

– Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.
– To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.
– Method overriding must have same : method name, data type, argument list.

How are virtual functions implemented in C++?

– Virtual functions are implemented using a table of function pointers. It is called the vtable.
– There exists one entry in the table per virtual function in the class.
– The table is created by the constructor of the class.
– When a derived class is constructed, its base class is constructed first. This creates the vtable.
– The derived class may override some of the base classes virtual functions. Such entries in the vtable are overwritten by the derived class constructor. For this reason, the virtual functions should not be called from a constructor.

What happens when you make call “delete this;”?

The two pit-falls exist here,
1. If it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement gets executed.
2. When an object finishes like this, the using program might not know about this end. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object is finished. Subsequent dereferencing of the pointer can lead to disaster.

Differentiate between a copy constructor and an overloaded assignment operator?

– A copy constructor constructs a new object by using the content of the argument object while an overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.
– Copy Constructor invoke in cases, such as:
i. Creation and initialization of an object simultaneously.
ii. When an object is passed to a function by value.
iii. When an object is returned from a function by value.

Explain Stack & Heap Objects?

The memory a program uses is divided into four areas :
1. The code area :
This is where the compiled program sits in memory.
2. The global area :
The place where global variables are stored.
3. The heap :
The place where dynamically allocated variables are allocated from.
4. The stack :
The place where parameters and local variables are allocated from.

Explain deep copy and a shallow copy?

a. Deep copy :
It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining objects.

b. Shallow copy :
It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable.This happens because of the straight copying of references and pointers.

Explain virtual class and friend class?

Virtual Base Class :
– It is used in context of multiple inheritance in C++.
– If you want to derive two classes from a class, and further derive one class from the two classes in the second level, you need to declare the uppermost base class as ‘virtual’ in the inherited classes.
– This prevents multiple copies of the uppermost base class data members when an object of the class at the third level of hierarchy is created.

b.) Friend class:
– When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods.
– Friendship is not necessarily bi-directional. If A declares B as its friend it does not imply that A can access private data of B. It only means that B can access all data of A.

Explain the scope of resolution operator?

– A scope resolution operator (::) is used to define the member functions of a class outside the class.
– Mostly, a scope resolution operator is required when a data member is redefined by a derived class or an overriden method of the derived class wants to call the base class version of the same method.

List the advantages of inheritance?

– Inheritence permits code reusability.
– Reusability saves time in program development.
– It encourages the reuse of proven and debugged high-quality software which reduces the problems after a system becomes functional.

Differentiate between declaration and definition?

The declaration informs the compiler that at some later point we plan to present the definition of this declaration.

Explain RTTI?

– RTTI – Runtime type identification
– It lets you find the dynamic type of an object when you have only a pointer or a reference to the base type.
– RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference.

Difference between struct and class in terms of Access Modifier?

Classes and structures are syntactically similar. In C++, the role of the structure was expanded, making it an alternative way to specify a class. In C, the structures include data members, in C++ they are expanded to have function members as well. This makes structures in C++ and classes to be virtually same. The only difference between a C++ struct and a class is that, by default all the struct members are public while by default class members are private.

How a modifier is similar to mutator?

A modifier is also known as mutator where the change in the member function value will change the value of a data member that is associated with the function. It modifies the state of an object that is why mutator as it mutates or makes duplicate copies of itself to be used so that by one function many things can be changed at a time.

What are the various operations performed on stack?

Various operations which can be performed on stack are as follows :
creatempty() : It creates an empty stack by initializing TOP to -1.
Isempty() : It determines whether stack is empty or not. It returns value 1 if stack is empty otherwise return 0.
   Push() :  Adding a new element at the top of the stack is called Push.
   Pop() :    Removing an element from the top of the stack is called Pop.

Summary
Review Date
Reviewed Item
Excellent!! C++ Interview Questions and Answers, Thank you so Much.
Author Rating
51star1star1star1star1star