Latest Qualification Jobs


ENTER YOUR E-MAIL FOR FREE JOB ALERTS RIGHT INTO YOUR INBOX -
AFTER THIS, YOU WILL NOT MISS ANY GOVT/PVT VACANCY
Check Your Email To Activate the Confirmation Link

C++ Interview Questions Answers | Top 30 Commonly Asked C++ Programming Ques

C++ Interview Questions Answers

We are providing C++ Interview Questions Answers for Fresher’s and Experienced who wants to get into software industry. Regardless of domain or language if you would like to pursue your career in then 90% of placement interviews include questions from C or C++.

These solved Top 30 Commonly Asked C++ Programming Ques will help you to prepare for technical interviews and online selection tests during campus placement for freshers and job interviews for professionals.

C++ Interview Questions and Answers for Freshers, Experienced

After reading these tricky C++ questions, you can easily attempt the objective type and multiple choice type questions on C++ Programming. When answering these questions please make sure you don’t give the text book explanations, instead give examples from real software scenario.

Aspirants can download C++ Interview Questions Answers in PDF format from below section of this page which is well created by the dedicated team members of recruitmentresult.com.

Interview Tips – Complete Guide Helps You In Cracking Interview

C++ Interview Questions Answers

Both Freshers and experienced who wish to get recruited in leading companies like Wipro, TCL , HCL etc you need to prepare for C++ Interview Questions Answers .

Top 30 Commonly Asked C++ Programming Ques

Question1) What is C++?

Answer: C++ is an object oriented programming language created by Bjarne Stroustrup. It is released in 1985.

Question2) What are the advantages of C++?

Answer: C++ doesn’t only maintains all aspects from C language, it also simplify memory management and add several features like:

  • Includes a new datatype known as a class.
  • Allows object oriented programming.

Question3) What is the difference between C and C++?

Answer:

No.CC++
1)C follows the procedural style programming.C++ is multi-paradigm. It supports both procedural and object oriented.
2)Data is less secured in C.In C++, you can use modifiers for class members to make it inaccessible for outside users.
3)C follows the top-down approach.C++ follows the bottom-up approach.
4)C does not support function overloading.C++ supports function overloading.
5)In C, you can’t use functions in structure.In C++, you can use functions in structure.
6)C does not support reference variables.C++ supports reference variables.
6)In C, scanf() and printf() are mainly used for input/output.C++ mainly uses stream cin and cout to perform input and output operations.

Question4) What is the difference between reference and pointer?

Answer:

No.ReferencePointer
1)References are less powerful than pointers. Once a reference is created, it can’t refer to other object later.Pointers provide the powerful facilities than references.
2)References are safer and easier to use than pointers.Pointers are comparatively difficult to use.

Question5) What is a class?

Answer: Class is a user-defined data type. Class defines the type definition of category of things. It defines a datatype, but it does not define the data it just specifies the structure of data.

You can create N number of objects from a class.

Check Here – Interview Tips For Freshers

Question6) What is an object?

Answer: Object is the instance of a class. A class provides a blueprint for objects. So you can create an object from a class. The objects of a class are declared with the same sort of declaration that we declare variables of basic types.

Question7) What are the C++ access specifiers?

Answer: The access specifiers are used to define how to functions and variables can be accessed outside the class.

There are three types of access specifiers:

  • Private: Functions and variables declared as private can be accessed only within the same class and they cannot be accessed outside the class they are declared.
  • Public: Functions and variables declared under public can be accessed from anywhere.
  • Protected: Functions and variables declared as protected cannot be accessed outside the class except a child class. This specifier is generally used in inheritance.

Question8) What is Object Oriented Programming (OOP)?

Answer: OOP is a methodology or paradigm that provides many concepts. The basic concepts of Object Oriented Programming are given below:

Classes and Objects: Classes are used to specify the structure of the data. They define datatype. You can create any number of objects from a class. Objects are the instances of classes.

Encapsulation: Encapsulation is a mechanism which binds the data and associated operations together and thus hide the data from outside world. Encapsulation is also known as data hiding. In C++, It is achieved using the access specifiers i.e. public, private and protected.

Abstraction: Abstraction is used to hide the internal implementations and show only the necessary details to the outer world. Data abstraction is implemented using interfaces and abstract classes in C++.

Some people confused about Encapsulation and abstraction. But they both are different.

Inheritance: Inheritance is used to inherit the property of one class into another class. It facilitates you to define one class in term of another class.

Question9) What is the difference between array and a list?

Answer:

  • Array is a collection of homogeneous elements while list is a collection of heterogeneous elements.
  • Array memory allocation is static and continuous while List memory allocation is dynamic and random.
  • In Array, users don’t need to keep in track of next memory allocation while In list user has to keep in track of next location where memory is allocated.

Question10) What is the difference between new() and malloc()?

Answer:

  • new() is a preprocessor while malloc() is a function.
  • There is no need to allocate the memory while using “new” but in malloc() you have to use sizeof().
  • “new” initializes the new memory to 0 while malloc() gives random value in the newly allotted memory location.

Know About – Interview Questions And Answers

Question11) 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));

Answer: 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.

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

int i = 5;

int j = i++;

Answer: 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.

Question13) Assuming buf is a valid pointer, 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 */

}

Answer: 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 */

}

Question14) 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();

}

Answer: 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.

That said many compilers will automatically optimize the first option by converting it into the second.

Question15) 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.

Answer: 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;

}

Read Here – Common Interview Mistakes That Candidates Make During Interview

Question16) What is a class?

Answer: 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 cannot stay inside blueprint of building, and you need to construct building 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

}

};

 Question17) What is an Object/Instance?

Answer: 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, 4 tyres etc.

Question18) What do you mean by C++ access specifiers ?

Answer: Access specifies are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifies 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.

Question19)  What are the basics concepts of OOP?

Answer:

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 shows 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 without 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 Symmetric Shape. 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.

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

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

int a = 10;

while( a == 10){

// Do something

}

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 won’t apply any optimization. This matters only in case of multi-threaded applications.

Get HereHow To Overcome Job Interview Fear

Question21) Explain what are Operators and explain with an example?

Answer: Operators are specific operands in C++ that is used to perform specific operations to obtain a result. The different types of operators available for C++ are Assignment Operator, Compound Assignment Operator, Arithmetic Operator, Increment Operator and so on.

For example arithmetic operators, you want to add two values a+b

1

2

3

4

5

6

7

8

9

10

11

12

#include

Using namespace std;

 

main ()

{

int a= 21 ;

int b= 10 ;

int c;

c= a + b;

cout << “Line 1- Value of c is : ” << c << endl ;

return 0;

}

It will give the output as 31 when you run the command

Question22) What is the C-style character string?

Answer: The string is actually a one-dimensional array of characters that is terminated by a null character ‘\0’.

1

2

3

4

5

6

7

8

9

#include

Using namespace std;

Int main ()

{

char greeting[6] = { ‘H’ , ‘e’ , ‘l’ ,’l’ , ‘o’ , ‘\0’};

cout << “Greeting message:” ;

cout << greeting << endl;

return 0;

}

On executing this code it will give the result likeà greeting message: Hello

Question23) Explain what is a reference variable in C++?

Answer: A reference variable is just like a pointer with few differences. It is declared using & Operator. In other words, reference is another name for an already existing variable.

Question24) Explain what is Polymorphism in C++?

Answer: Polymorphism in C++ is the ability to call different functions by using only one type of the function call. Polymorphism is referred to codes, operations or objects that behave differently in a different context.

For example, the addition function can be used in many contests like

  • 5+5 à Integer addition
  • Medical+Internship à The same ( + ) operator can be used with different meaning with strings
  • 3.14 + 2.27 à The same ( + ) operator can be used for floating point addition

Question25) Explain what is data abstraction in C++?

Answer: Data abstraction is a technique to provide essential information to the outside world while hiding the background details. Here in below example you don’t have to understand how cout display the text “Hello guru99” on the user screen and at the same time implementation of cout is free to change

1

2

3

4

5

6

7

8

#include

Using namespace std;

 

int main ( )

{

Cout << “Hello guru99” <<endl;

return 0 ;

}

Know About – How To Dress For An Interview

Question26) Explain what is C++ exceptional handling?

Answer: The problem that arises during execution of a program is referred as exceptional handling. The exceptional handling in C++ is done by three keywords.

Try: It identifies a block of code for which particular exceptions will be activated

Catch: The catch keyword indicates the catching of an exception by an exception handler at the place in a program

Throw: When a problem exists while running the code, the program throws an exception

Question27) Explain what is data encapsulation in C++?

Answer: Encapsulation is an object oriented programming concept (oops) which binds together the data and functions. It is also referred as data hiding mechanism.

Question28) Mention what are the types of Member Functions?

Answer: The types of member functions are

  • Simple functions
  • Static functions
  • Const functions
  • Inline functions
  • Friend functions

Question29) Mention what are the decision making statements in C++? Explain if statement with an example?

Answer: The decision making statements in C++ are

  • if statement
  • switch statement
  • conditional operator
1

2

3

4

5

6

7

8

9

10

11

#include

Int main ( )

{

Int, x, y;

X= 10;

Y= 5;

If (x > y)

{

Cout << “x is greater than y”;

}

}

Question30) Explain what is multi-threading in C++?

Answer: To run two or more programs simultaneously multi-threading is useful. There are two types of

  • Process-based: It handles the concurrent execution of the program
  • Thread-based: It deals with the concurrent execution of pieces of the same program

Also CheckHow to Prepare For an Interview

Significant Words:

If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.

It really doesn’t matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence.

So just feel confident during your interview. And if you have any query or doubts related to C++ Interview Questions Answers then you may ask by typing your comment in below comment box. Our experts will soon solve your queries.

More Links Related To Interview

Computer Networking Interview QuestionsAdvanced Java Interview Questions
Digital Electronics Interview QuestionsJava Interview Questions
SQL Interview QuestionsDBMS Interview Questions
Java Programming Interview QuestionsData Structure Interview Questions
C Language Interview Questions.NET Interview Questions
Unix Interview QuestionsHR Interview Questions

Filed in: Interview

Leave a Reply

Submit Comment