C++ Interview Questions and Answers - Test & Download

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.
1 2 3 4 5 6 7 8

When is dynamic checking necessary? - C++
When is dynamic checking necessary? - Whenever the definition of a variable is not necessary before its usage....
Define structured programming - C++
Structured programming - Structured programming techniques use functions or subroutines to organize...
Explain object oriented programming.
Object oriented programming - Object oriented programming uses objects to design applications...
Post your comment
Discussion Board
Good
Very useful questions of C++.
But page is not so attractive. Please, change the UI
Pratik 08-15-2015
#14 is flat out wrong
#14 says:
"No, the code has a problem. The program will crash in an attempt to delete a null pointer. "

Contrary to popular believe, this is flat out incorrect. Calling delete on a null pointer is harmless. If you don't believe me, go write any of the following code and run it:

delete NULL;

delete nullptr;

int* foo = NULL;
delete foo;

I would recommend removing #14 from the list of questions.
John Selbie 06-12-2014
Advanced C++ interview questions - senior level C++ interview
Explain the public method for the data type conversions.

• A class may be having a public method for the specific data type conversions.

for example:

class B
{
double value;
public:
B(int i )
operator double()
{
return value;
}
};

B BObject;

double i = BObject; // the conversion operator is called to assign the value.


What is diff between malloc()/free() and new/delete?

• The malloc allocates memory for object in the heap but not invokes object's constructor for initiallizing the object.

• new also allocates thememory and also invokes constructor to initialize the object.

• malloc() and free() are not able to support object semantics but does not construct and destruct any objects

• string * ptr = (string *)(malloc (sizeof(string)))

• int *p = ( int * ) ( malloc ( sizeof(int) ) );

• int * p = new int;


new and delete,both can be overloaded in a class :

• "delete" first calls the object's termination routine and then releases the space the object occupied on the heap memory.

If an array of objects are created using new, then delete will be dealing with an array by preceding the name & with an empty [] :-

Int_t *my_ints = new Int_t[10];

...

delete []my_ints;


Define macro.

• There is no way for the compiling to verify that the macro parameters are of compatible types.

• The macro can be expanded without any special type checking.

• If macro parameter is having a post incremented variable ( like c++ ), the increment will be performed twice.

for example:

Macro:

#define min(i, j) ( i < j ? i : j )

template:
template
T min ( T i, T j )
{
return i < j ? i : j ;
}



What are C++ storage classes?

storage classes types are :

• auto: This the default . Variables are naturally created and initialized when they are defined and are destroyed at the end of the block contained their definition.

• register: It's a type of auto variable. This helps the compiler to use a CPU register for performance

• static: It's a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function.

• extern: It's a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file.

What is a virtual function?

• If the derived class overrides the base class method by redefining the same function, then if client will want to access redefined the method from derived class through a pointer from base class object, then we have to define this function in the base class as a virtual function.

class parent
{
void Show()
{
cout << "i'm parent" << endl;
}
};

class child : public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_ object_ ptr -> show() // calls parent->show() i

now we goto virtual world...

class parent
{
virtual void Show()
{
cout << "i'm parent" << endl;
}
};

class child : public parent
{
void Show()
{
cout << "i'm child" << endl;
}

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls child->show()


What is pure virtual function? or what is abstract class?

While we define function prototype in a base class without implementation .The base class is called abstract class

Example of a pure virtual function or abstract class this way..

class B
{
void f() = 0;
}

B MyB; // compilation error
Advanced C++ interview 07-18-2012
Basic C++ interview questions - Frequently asked C++ interview
Write some differences between an external iterator and an internal iterator? Describe the advantage of an external iterator.

• An external iterator gets implemented as a separate class that can be "attach" to the object which is having items to step through .

• In case of an internal iterator it is implemented with a member function of the class which are having the items to step through.

• With the help of an external iterator many different iterators can be activated simultaneously on the same object.


Verify the following code. Point out the problems.

T *p = 0;

delete p;

• No, the code has a problem.

• The program will be crashed for an attempt to delete a null pointer.


Incase of a function declaration, what is extern means?

• The extern tells the compiler regarding the existence of a variable or a function.

• The variable or function can be defined within another file


How can you link a C++ program to C functions?

This can be done Intwo methods ;

• First by using the extern "C" linkage specification

• The linkage is done in the C function declarations.

Define STL.

• STL stands for Standard Template Library.

• It is the library for container templates.

• This is approved by the ANSI committee for including in the standard C++ specification.

Name the different types of STL containers.

The 3 types of STL containers are:

• Adaptive containers - e.g. stack, queue,

• Associative containers - for e.g. set, map

• Sequence containers - e.g. vector, deque

What is Stack unwinding?

• Stack unwinding is the process for exception handling

• It takes place when the destructor is being called.

• The destructor calls all the local objects between the place where the exception had been thrown and where it had been caught.

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

We can find out if the linked-list is cycle or not by the use of two pointers:

• One of them will go 2 nodes

• Each time when the second one goes at node 1 .

• Incase there is a cycle, the one that goes 2 nodes each time will meet the one that goes slower. If this occurs, we can confirm that the linked-list is a cycle else not.


Define a nested class. Explain how it can be useful.

• A nested class is said to be a class which is enclosed in the scope of another class.

For example:

// Example : Nested class
//
class OuterClass
{
class NestedClass
{
// ...
};
// ...
};

• Nested classes are of great use for organizing code and for controlling access and dependencies.

• Nested classes do obey access rules.

So, if NestedClass is when public ,any code can be named as OuterClass::NestedClass.


When does the C++ compiler create temporary variables?

If the function parameter is a "const reference", the compiler generates temporary variables in the following 2 ways.

• a) If the actual argument is the correct type, but it isn't Lvalue

double Cubes(const double & num)
{
numb = numb * numb * numb;

return numb;

}

double temp = 2.0;

double value = cubes(3.0 + temp); // the argument is said to be an expression ,not the Lvalue;


• b) A type can be converted to the correct type

long temp = 3 L;

double value = cuberoot ( temp ) ;


Explain the differences between List x; & List x();.

There exists a big difference which is explained via a code below:

• Let, List is a name of any class.

Then function f() evokes a local List object x:

void f()

{

List x; // Local object x

...

}

But the function g() invokes f() which eventually returns a List:

void g()

{


List x(); // function which returns the List

...

}

What is conversion constructor?

• The constructor with a single argument is called as conversion constructor and it can be used for the type conversion.

for example:

class B
{
public:
B( int i );
};


B B Object = 10 ; // assigning int 10 B object
Basic C++ interview 07-18-2012
C++ interview questions and answers for freshers
Define Copy Constructor.

• It is a simple constructor.

• With a different object of the same class, it initializes it's object member variable.

• If we don't implement copy constructor, it does automatically.

When do we use copy constructors?

Copy constructors are called in these scenarios below:

• At the time of generating a temporary object by the compiler.

• If a function is returning an object of that particular class by value

• At the time of passing by value as an argument to a function by the object of that class

• At the time of constructing an object based on a different object of the same class

What are the implicit member functions of class?

The implicit member functions are

• default ctor

It is mainly used for initializing.

• copy ctor

It is used for creating a new object as a copy of the existing one.

• assignment operator

It is the operator used for assigning values to the variables.

• default destructor

It acts just like the inverse of constructor for de-initializing variables.

• address operator

It connects an operand to its pointer variable.

What are the storage qualifiers?

The storage qualifiers are:

• Const - If the memory gets initialized once, it will remain indifferent.

• Volatile - If the value in the memory location will be altered though nothing is changed in the program code, this value may be changed.

• Mutable - This means that if a member of a structure or class can be altered though a particular structure variable, class, or class member function will remain constant.

What is dangling pointer?

• Pointer that does not point to a proper or valid object of the correct type is called Dangling pointer.

• If the address of an object is used after its lifetime, the concept of dangling pointer will come.

The examples of such situations can be given as:

• To return the addresses of any automatic variable from the function or by using the address of the memory block after it has got freed.

Do we have to use initialization list in spite of the assignment in constructors?

• We can use non-static const data members and reference data members.

• We have to use initialization list for initializing them.

When does a class need a virtual destructor?

• If our class has at least one virtual function, we have to have a virtual destructor.

• This will allow deleting a dynamic object.

• In absence of this, the wrong destructor will be invoked during deletion of the dynamic object.

What is type of “this” pointer? Explain when it is get created?

• ''this' is a constant pointer type.

• It will get created if a non-static member function of the class is called up.

How we can differentiate between a pre and post increment operators during overloading?

• We have to mention the keyword int as the second parameter

• It is to be mentioned the post increment form of the operator++() .

Define a pdb file.

• It's a program database (PDB) file.

• This file contains debugging and project state information which does the incremental linking of a Debug configuration for the program.

• This file gets created at the time of compiling a C/C++ program with the help of /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug.

When do we run a shell in the UNIX system? How will you tell which shell you are running?

• For checking this we can simply run the command Echo $RANDOM.

Thus the results obtained will be:

• Undefined variable if we'll do this in the C-Shell.

• A return prompt will be available if we'll execute in the Bourne shell,

• A 5 digit random number will be available if we’ll execute in the Korn shell.

• We can also run a ps -l and look for the shell having the highest PID.

Define Stacks. Provide an example where they are useful.

• A Stack is of course a linear structure.

• In stack insertions and deletions are being made at the one end i.e the top - which is termed as last in, first out (LIFO).

• Application of Stacks can be used when we need to debug some syntax errors like missing parentheses.
Freshers C++ questions 07-18-2012
C++
Answer of question 14 is wrong.
Code will work fine. There should be no problem in deletion of NULL pointer.
If pointer is uninitialized then only it will crash.
Madhumita 03-20-2012
C++ interview questions and answers
What is the type of “this” pointer?

It is a constant pointer.

When does a “this” pointer get created?

When a non-static member function of a class is called.

Define VPTR.

The address of the VTABLE stored in the object is known as VPTR.

Define upcasting.

Storing the address of the derived class object in the base class pointer.

Explain how to initialize a const data member.

The const data member can be initialized with constructor initializer list.
Jitendra 12-5-2011
C++ interview questions and answers
Explain the difference between C++ and Java.

C++ has pointers whereas Java does not.
Java is platform independent whereas C++ is not.
Java has garbage collection whereas C++ does not.

Define virtual constructor.

There is no such concept in C++.


Define anonymous class.

A class that is defined without any name is called anonymous class.

Explain how to initialize a const member data.

Use constructor initializer list.

Difference between delete and free.

Delete invokes destructor, free will not
Kavita 12-5-2011
C++ interview questions and answers
Define destructor.

Destructor destroys any extra resources allocated by the object.

Define default constructor.

Constructor with no arguments or all the arguments has default values.


Define copy constructor.

It initializes it's object member variables with another object of the same class.


Define Default assignment operator.

It handles assigning one object to another of the same class.


What are storage qualifiers in C++ ?

const, volatile, mutable

What is a dangling pointer?

A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.
Rakesh 12-5-2011
C++ interview questions and answers
Brief about mutable member.

mutable member can be modified by the class.

Is C an object-oriented language?

C is not an object-oriented language.


What are the traits of an object-oriented language?

Encapsulation, inheritance, and polymorphism

Define pure virtual function.

A pure virtual function is one with an initializer of = 0 in its declaration

What is semaphore?

Semaphore performs atomic operations, once a semaphore is called it can not be interrupted.


Define constructor.

Constructor creates an object and initializes it.
It also creates vtable for virtual functions.
Neelam 12-5-2011
C++ interview questions and answers
Define an object.

Objects have state and behavior and it is a bundle of variables and related methods.

Name the keyword used when defining a function in base class to allow this function to be a polimorphic function.

virtual

What do you understand by binding of data and functions?

Encapsulation.

Define a class.

Class is a user-defined data type in C++.
After creation the user need not know the specifics of the working of a class.


Can you show the way to link a C++ program to C functions?

You can do so by using the extern "C" linkage specification around the C function declarations.

Define a conversion constructor.

A constructor that accepts one argument of a different type.
Rajesh 12-5-2011
C++ interview questions and answers
Explain the advantages of inheritance.

Inheritance allows code reusability that saves time in program development.
It encourages the reuse of proven and debugged high-quality software.


Define inline function.

Inline functions is to insert the code of a called function at the point where the function is called.
Improve the application's performance in exchange for increased compile time.


Does c++ support multilevel and multiple inheritance?
Yes.

Define encapsulation
Encapsulation is keeping an object’s variables within its methods.

What is abstraction?

Abstraction is of the process of hiding unwanted details from the user.

Raj 12-5-2011
C++ Interview questions Answer
Nice link, quite helpful, thanks for posting such an exhaustive interview series
Nitin P 11-8-2011