C++ Interview Questions and Answers For Freshers, Experienced
C++ Interview Questions and Answers For Freshers, Experienced
Freshers, Experienced
5
174 Votes
Hits: 110616
We are providing comprehensive set of C++ Interview Questions and Answers for Freshers and
Experienced who wants to get into software industry. It's regardless of which domain or language
you would like to pursue your career in, because 90% of campus placement interviews include
questions from C or C++. The main reason being a candidate who is fresh out of college is not
expected to be a master of widely used languages like Java, Python, Perl etc. and most of the
universities have C or C++ as a part of their curriculum. For example, in most institutions C language
is being taught along with data structure course and C++ as part of Object oriented programming. So
always expect questions on C/C++ in the technical interviews for fresher.
One advantage with fresher interviews is that there are only limited number of concepts and
questions and the same has been repeatedly being asked over years. If you want to pursue your career
in system level programming like driver development, needless to say, you should show your
mastery in C/C++ interviews. Here we have identified and collected a set of frequently asked C++
interview questions and answers for experienced and freshers as well. It's a continuously updated list,
go through them, understand the concepts and excel in the interviews.
4. intnumberOfTyres;
5. doubleengineCapacity;
6. voiddrive(){
7. //codetodrivethecar
8. }
9. };
3. 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
1. VehiclevehicleObject;
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.
4. 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.
how you apply these OOPs concepts in real life. You should be able to give real life examples for
each of these concepts, so prepare yourself with few examples before appearing for the interview. It
has seen that even the experienced people get confused when it comes to the difference between basic
OOP concepts, especially abstraction and encapsulation.]
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
1. classPerson
2. {
3. private:
4. intage;
5. public:
6. intgetAge(){
7. returnage;
8. }
9. intsetAge(intvalue){
10. if(value>0){
11. age=value;
12. }
13. }
14. };
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.
1. classStack
2. {
3. public:
4. virtualvoidpush(int)=0;
5. virtualintpop()=0;
6. };
7.
8. classMyStack:publicStack
9. {
10. private:
11. intarrayToHoldData[];//Holdsthedatafromstack
12.
13. public:
14. voidpush(int){
15. //implementpushoperationusingarray
16. }
17. intpop(){
18. //implementpopoperationusingarray
19. }
20. };
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.
1. classSymmetricShape
2. {
3. public:
4. intgetSize()
5. {
6. returnsize;
7. }
8. voidsetSize(intw)
9. {
10. size=w;
11. }
12. protected:
13. intsize;
14. };
15.
16. //Derivedclass
17. classSquare:publicSymmetricShape
18. {
19. public:
20. intgetArea()
21. {
22. return(size*size);
23. }
24. };
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.
6. 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. inta=10;
2. while(a==10){
3. //Dosomething
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 c++, variables can be initialized in two ways, the traditional C++ initialization using "=" operator
and second using the constructor notation.
In the above example, variable a will get automatically promoted from short to int. This is called
implicit conversion/coercion in c++.
9. 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.
1. inlineintmin(inta,intb)
2. {
3. return(a<b)?a:b;
4. }
5.
6. intmain()
7. {
8. cout<<"min(20,10):"<<min(20,10)<<endl;
9. cout<<"min(0,200):"<<min(0,200)<<endl;
10. cout<<"min(100,1010):"<<min(100,1010)<<endl;
11. return0;
12. }
If the complier decides to make the function min as inline, then the above code will internally look as
if it was written like
1. intmain()
2. {
3. cout<<"min(20,10):"<<((20<10)?20:10)<<endl;
4. cout<<"min(0,200):"<<((0<200)?0:200)<<endl;
5. cout<<"min(100,1010):"<<((100<1010)?100:1010)<<endl;
6. return0;
7. }
Minus source code lines ignored by any conditional pre processing directives ( the lines
ignored by #ifdef,#ifndef etc)
11. What do you mean by internal linking and external linking in c++?
[This interview question is related to questions on "translation unit" and "storage classes"]
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.
12. 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.
13. 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.
1. voidchangeValue(void)
2. {
3. autointi=1;
4. i++;
5. printf("%d",i);
6.
7. }
8. intmain()
9. {
10. changeValue();
11. changeValue();
12. changeValue();
13. changeValue();
14. return0;
15. }
16.
17. Output:
18. 2222
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.
1. intmain()
2. {
3. registerinti;
4. intarray[10]={0,1,2,3,4,5,6,7,8,9};
5.
6. for(i=0;i<10;i++)
7. {
8. printf("%d",array[i]);
9. }
10. return0;
11. }
12.
13. Output:
14. 0123456789
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.
1. voidchangeValue(void)
2. {
3. staticinti=1;
4. i++;
5. printf("%d",i);
6.
7. }
8.
9. intmain()
10. {
11. changeValue();
12. changeValue();
13. changeValue();
14. changeValue();
15. return0;
16. }
17.
18. Output:
19. 2345
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.
1. intx=10;
2. intmain()
3. {
4. externinty;
5. printf("x:%d",x);
6. printf("y:%d",y);
7. return0;
8. }
9. inty=70;
10.
11. Output:
12. x:10y: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.
1. classTest
2. {
3. public:
4. Test():x(1),y(1){};
5. mutableintx;
6. inty;
7. };
8.
9. intmain()
10. {
11. constTestobject;
12. object.x=123;
13. //object.y=123;
14. /*
15. *Theabovelineifuncommented,willcreatecompilationerror.
16. */
17. cout<<"X:"<<object.x<<",Y:"<<object.y;
18. return0;
19. }
20.
21. Output:
22. 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
register
CPU register
Local
With in function
extern
Memory
(RAM)
Global
6. SampleClass(SampleClass&obj);
7. };
8.
9. SampleClass::SampleClass(){
10. ptr=newint();
11. *ptr=5;
12. }
13.
14. //Copyconstructordefinition
15. SampleClass::SampleClass(SampleClass&obj){
16. //createanewobjectforthepointer
17. ptr=newint();
18. //Nowmanuallyassignthevalue
19. *ptr=*(obj.ptr);
20. cout<<"Copyconstructor...\n";
21. }
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().
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.
16. 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.
17. What do you mean by persistent and non persistent objects?
[This question may be asked in many ways during c++ interviews, like how to send an object to a
remote computer or how to save the your program state across application restarts. All these are
related to serialization.]
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. ]
18. 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.
1. classBase
2. {
3. inta;
4. public:
5. Base()
6. {
7. a=1;
8. }
9. virtualvoidmethod()
10. {
11. cout<<a;
12. }
13. };
14.
15. classChild:publicBase
16. {
17. intb;
18. public:
19. Child()
20. {
21. b=2;
22. }
23. virtualvoidmethod()
24. {
25. cout<<b;
26. }
27. };
28.
29. intmain()
30. {
31. Base*pBase;
32. ChildoChild;
33. pBase=&oChild;
34. pBase>method();
35. return0;
36. }
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.
20. 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,
1. classSymmetricShape{
2. public:
3. //draw()isapurevirtualfunction.
4. virtualvoiddraw()=0;
5. };
21. 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.
22. 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.
23. 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.
For all the direct function references compiler will replace the reference with actual address of the
method.
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.
24. 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).
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. inta=20;
2. int&b=a;
3.
The first statement initializes a an integer variable a. Second statement creates an integer reference
initialized to variablea
Take a look at the below example to see how reference variables work.
1. intmain()
2. {
3.
inta;
4.
int&b=a;
5.
6.
a=10;
7.
cout<<"Valueofa:"<<a<<endl;
8.
cout<<"Valueofareference(b):"<<b<<endl;
9.
10.
b=20;
11.
cout<<"Valueofa:"<<a<<endl;
12.
cout<<"Valueofareference(b):"<<b<<endl;
13.
14.
return0;
15. }
Reference Variables
Technical Support
Application Support or Technical support (also tech support) is a range of services providing assistance with
technology products such as mobile phones, televisions, computers, software products or other electronic or
mechanical goods. In general, technical support services attempt to help the user solve specific problems with a
productrather than providing training, customization, or other support services. Most companies offer technical
support for the products they sell, either freely available or for a fee.
Technical support may be delivered over the telephone or online by e-mail or a web site or a tool where users can log
a call/incident. Larger organizations frequently have internal technical support available to their staff for computer
related problems. The internet is also a good source for freely available tech support, where experienced users may
provide advice and assistance with problems. In addition, some fee-based service companies charge for premium
"Give me an example when you had to simplify complex information in order to explain it to a caller.
ANSWER: Key to your performance on the help desk is an ability to break down complicated information so that it
can be easily understood by people with limited technological expertise. Your answer should show how you can
express your knowledge in a clear and simple manner.
3.
ANSWER:To describe your interpersonal skills you can tell them about the instances form your work that will help
them to relate to the skills. Whatever qualities that you have can be described. It will help them to better understand
you and your intentions. But dont use flowery language at all. Be simple and clear while answering.
4.
ANSWER: According to your past experiences you can give this answer. If the answer is yes then tell them the
reason behind it and how did you managed to resolve their problems and how much time was consumed. But dont
try to fool them as they are smarter and have the capability to catch you.
5.
ANSWER: In this question you can list all the experience that you have while working in any of the organization. If
you want you can also add the new things that you have explored to let them know that you are a quick learner. The
experience can also include your working style too.
6.
ANSWER: As it is a job that requires keen attention therefore you must be attentive in listening and answering such
questions. So if you try to befool them they will surely understand and you will be easily caught. So always be true to
any information that you furnish.
7.
ANSWER: An organized person is one who is particular about his routines and strictly follows the schedule that is
given to them. The targets have to be achieved within the specified limits. So support your answers with evidences
and facts.
8.
ANSWER: This a question that tests how you handled your relationship with your ex-boss and if you are to speak ill
of your boss. If you fall for it and tell about a problem with a former boss, you may well below the interview right there.
Stay positive and develop a poor memory about any trouble with a supervisor.
9.
Tell me how you have dealt with a hostile caller. What was the outcome?"
ANSWER:"Describe a highly stressful interaction you've had with an internal/external customer. How did your
react?"
"How did you respond when you received negative feedback from a caller about you personally?" These help desk
interview questions require you to show how you can handle negative and stressful situations. Your answer should
show a patient and positive attitude when challenging situations occur and that you do not allow your personal ego to
get in the way of helping the caller. Describe the coping techniques you use to keep calm under stress.
10. "Tell me about your current work schedule."
ANSWER: Help desk staff may be required to work outside the 9 to 5 day. Your willingness to have a flexible
work schedule may be explored.
11. "How do you keep your knowledge and skills current?"
ANSWER: Demonstrate a willingness to learn and implement new knowledge. They need to constantlylearn new
technologies and stay current
12. "In which areas do you consider yourself to be an expert, and how do you envisage being able to utilize this
expertise within this organization?"
ANSWER: Demonstrate that you understand the overall systems environment as well as specific products.
Highlight your specialist skills and how they will benefit this position.