C++ Interview Questions & Answers (Prepared by Industry Experts)

Free C++ course with real-time projects Start Now!!

Wouldn’t it be great if you were aware of the C++ questions that would be asked in your next interview? While you cannot read the mind of the interviewer, you can certainly anticipate questions with our collection of important C++ interview questions and their solutions.

These C++ questions will assist you in cracking interviews. You will be much more confident about taking on interviews after you have bolstered your foundations with these quintessential questions.

So, ace your interviews and jumpstart your career.

Latest C++ Interview Questions

Q.1 What is the difference between a reference and a pointer?

Ans. Pointers and References are two different concepts. A pointer in C++ is basically a variable that stores the memory address of another variable. While references act as an alias name for an existing variable that needs to be initialized at the time of declaration. This is not the case with pointers.

Here are a few more differences between the two:

PointersReference 
In any C++ program, a pointer has the provision to point to several objects.In any C++ program, references can only refer to only one object, that is, a reference cannot rebound.
We can create an array of pointersWe cannot create an array of references as it is impossible to initialize a value to each element of the array at the time of declaration.
The “*” operator is needed to de-reference a pointerNo such operator is required to de-reference an operator.
A pointer can hold a NULL valueA reference cannot hold a null value

Q.2 What was the need to introduce classes when C++ already supports structures?

Ans. Classes and objects in C++ provide a way to implement the concept of object-oriented programming like data abstraction, encapsulation, hiding, inheritance, and polymorphism. These features help in representing real-world problems and propose algorithms to solve them.

These features cannot be implemented with the help of structures.

For instance, the public, private and protected mode of a class helps in keeping the data secure whereas, in structures, there is only visibility mode, that is, public by default that does not ensure any data security.

Q.3 Which is the most preferred loop for traversing an array and why?

Ans. The most preferable loop for traversing an array is the “for loop” since an array uses the index of the element for traversal. Using the for loop ensures easy access to the element.

For instance,

Array [ 5 ] = {10, 20, 30, 40, 50}

Using the for loop in C++,

for (int i = 0; i < 5; i++ )
{
cout << Array [ i ];
}

Basically, an iterative block is required along with a looping variable ‘i’ serving an index counter, incrementing from:

0 to ((length of the array) – 1)

Get the Samurai Technique to Learn Arrays in C++

Q.4 What is the difference between the local and global scope of a variable and what is their order of precedence if they both are of the same name?

Ans. The local scope of a variable allows the variable to work inside a restricted block of code. For instance, if it is declared inside a function, you cannot access it from the main function without calling the function whereas the global scope of a variable allows the variable to be accessible throughout the entire program.

It is a well-established fact that whenever a program has a local and global variable, precedence is given to the local variable within that program.

Q.5 What is the difference between a++ and ++a?

Ans. a++ refers to post-increment operation. The C++ compiler first uses the value of a and then increments it.

++a refers to the pre-increment operation. The C++ compiler first increments the value of a++ and then uses a.

Q.6 How would you establish the relationship between abstraction and encapsulation?

Ans. Data abstraction refers to representing only the important features of the real-world object in the C++ program. This entire process does not include any explanation and background details of the code. Abstraction is implemented with the help of classes and objects, whereas, data encapsulation is the most significant feature of a class.

Data encapsulation in C++ refers to the wrapping up of data members and member functions that operate on the data as a single unit, called the class. Encapsulation prevents free access to the members of the class.

Q.7 How is object-oriented programming different from procedural programming?

Ans. In object-oriented programming, the entire program is divided into smaller units called objects and works on the bottom-up approach. Whereas, in procedural programming, the entire program is divided into smaller units called functions and works on the top-down approach.

In a nutshell, procedural programming does not provide any data security whereas, in contrast to it, object-oriented programming ensures data security with the help of access specifiers, proving to be more secure and efficient.

C++ supports object-oriented programming whereas C supports procedural programming.

Q.8 What are the similarities between constructors and destructors?

Ans. Both constructors and destructors in C++ need to be declared within the class with the same name as that of the class. Even if they aren’t declared inside the class, they exist by default but in this case, we can use them only to allocate and deallocate memory from the objects of a class, whenever the object is declared or deleted.

Q.9 Why cannot a constructor and destructor be inherited?

Ans. Both constructors and destructors are not inherited as each class have its own constructor. Since each object of a class consists of multiple parts, a base class part and derived class part, constructors and destructors are not inherited.

Q.10 Consider the following C++ code segment and answer the following questions associated with it:

#include <iostream>
using namespace std;

class Test
{
int ID;
float max, min, marks;
public: 
Test() // Function 1
{
ID = 121;
max = 100;
min = 33.33;
marks = 75;
}

Test(int r_no, int Marks) // Function 2
{
ID = r_no;
max = 100;
min = 33.33;
marks = Marks;
}

~Test() // Function 3
{
cout<<"Finished Test"<<endl;
}
void display() // Function 4
{
cout<<ID<<"\t"<<max<<"\t"<<"\t"<<min<<endl;
cout<<"Your marks: "<<marks<<endl;
}
}

Q.10.1 Which OOP concept is illustrated through “Function 1” and “Function 2” together?

Ans. The concept of polymorphism and constructor overloading is represented by both the functions together.

Learn everything about Polymorphism in C++

Q.10.2 What is “Function 3” referred as and when would it be invoked?

Ans. Function 3 refers to the destructor of the class. It is invoked as soon as the scope of the object of the class gets over.

C++ Coding Interview Questions and Answers

Q.11 Predict the header files required to run this program and its output: (i1)

(NOTE that the ASCII value of ‘A’ is 65)

using namespace std;

int main()
{

char letter = 'A', new_letter;
int value = 10, result;
if(islower(letter))
new_letter = toupper(letter);
else 
new_letter = value + letter;
result = new_letter + 10;
cout<< letter <<" has changed its value to " << result <<endl;
return 0;
}

Ans. The required header file is <ctype.h>

OUTPUT: A has changed its value to 85.

You can create your Header Files in C++ in a few seconds.

Q.12 Predict the output of the following code:

#include <iostream>
using namespace std;

class Gameplay
{
int level, points;
char type;
public:
Gameplay(char Gtype = 'A')
{
level = 1;
points = 0;
type = Gtype;
}
void play(int g);
void upgrade();
void display()
{
cout<<type<<"*"<<level<<endl;
cout<<points<<endl;
}
};

int main()
{

Gameplay g1('P'), g2;
g2.display();
g1.play(10);
g1.upgrade();
g2.play(20);
g1.display();
g2.display();
}

void Gameplay :: upgrade()
{
type = (type=='A')?'P':'A';
}
void Gameplay :: play(int g)
{
points = points + g;
if(points > 50)
level = 5;
else if(points > 40)
level = 4;
else
level = 3;
}

Ans.

A*1
0
A*3
10
A*3
20

Q.13 Consider the following C++ code segment and answer the following questions associated with it:

class College
{
long ID;
string city;
protected:
string Country;
public:
College();
void enroll();
void print();
};
class Department :: private College
{
long Dcode[20];
string HOD;
protected:
double budget;
public:
Department();
void enter();
void display();
};
class Student : public Department
{
long r_no;
string name;
public:
Student();
void get_admission();
void view();
};

Q.13.1 Which type of inheritance is illustrated through the above C++ code?

Ans. The concept of multilevel inheritance has been illustrated through the above C++ code.

Q.13.2 Which member functions are directly accessible from the objects of the class “Student”?

Ans. The member functions that are directly accessible through the objects of class “Student” are:

get_admission();
view();
enter();
display();

Q.13.3 Is it possible to directly call the function “print()” of class Campus from an object of class “Department”?

Ans. In the above code segment, it is not possible to call the function “print()” of class Campus as there is no such class named “Campus” in the given program.

Q.13.4 Which data members are directly accessible from the member functions of the class “Student”?

Ans.The data members that are directly accessible to the member function “Student” are:
r_no;
name;
budget;

Master the concept of Functions in C++ with Example

Q.13.3 Write a C++ function to count the number of lowercase alphabets in a text file.

Ans.

int count_lowercase()
{
ifstream fin("file_name.txt");
char ch;
int count = 0;
while(!fin.eof())
{
fin>>ch;
is(islower(ch))
count++;
}
fin.close();
return count;
}

Q.14 If you are given a binary file named “Phone.dat” that consists of records of a phonebook directory, how would you copy the records of the file that have their AreaCode as “400” from “Phone.dat” to “Copy.dat”?

The given binary file has the following content:

class Directory
{
string name, address;
char phone_no[15];
char area_code[5];
public:
void input();
void output();
int checkcode(string ac)
{
return strcmp( area_code, ac)
}
};

Ans. We will define a function to perform the above-stated task:

void copy400()
{
ifstream fin;
ofstream fout;
Directory ph;
fin.open("Phone.dat", ios::in | ios::binary);
fout.open("Copy.dat", ios::out | ios::binary);
while(!fin.eof())
{
fin.read((char*)&ph. sizeof(ph));
if(ph.checkcode("400")==0)
fout.write((char*)&ph, sizeof(ph));
}
fin.close();
fout.close();
}

Q.15 Write a C++ function to perform popping operation from a dynamic stack that contains the name of a book and its title. Consider the following definition:

struct node
{
int book_no;
char book_name[30];
node *link;
};

Ans. The function definition to pop the elements in the stack is as follows:

void POP(node *top)
{
cout<<"Popping the top element from the stack"<<endl;
cout<<"The book number is: "<< top->book_no <<endl;
cout<<"The book name is: "<< top -> book_name <<endl;
node *temp = top;
top = top -> link;
delete(temp)
}

Q.16 Write a C++ function to perform insertion operation in a dynamic queue according to the following code definition:

struct node
{
int ID;
char name[100];
node* next;
};

Ans. The function definition to insert the elements in the queue is as follows:

void ENQUEUE(node *rear, int val, char data[])
{
node*temp = new node;
temp -> ID = val;
strcpy(temp -> name,data);
temp -> next = NULL;
if(rear == NULL)
rear = front = temp;
else
{
rear -> next = temp;
rear = temp;
}
}

Q.17 How would you find the sum of two numbers without using the ‘+’ operator in C++?

Ans. Here is a program that helps you find the sum of two numbers without using the ‘+’ operator in C++:

#include<iostream> 
using namespace std;

void sum(int n1, int n2)
{
int sum = -( -n1-n2 ); 
cout << sum << endl; 
}
int main() 
{
sum(5,5);
sum(6,4); 
return 0;
}

Q.18 Find out the error in the following code segment in C++

int main()
{

const int val = 10;
const int *const pointer = &val;
(*pointer)++;
int data = 20;
pointer = &data;
}

Ans. It is an evident fact that the statements “(*pointer)++” and “pointer = &data” cannot modify a constant object as the value of a constant variable cannot change throughout the entire program.

Q.19 What is the difference between typecasting and automatic type conversion? Explain with the help of an example.

Ans. Typecasting in C++ is done by the programmer in order to convert a value from one data type to another data type.

For example,

float pi = (float) 22/7;

On the other hand, automatic type conversion is automatically done by the C++ compiler as and when required.

For example,

float value = 10;

Q.20 Why do we use templates in C++?

Ans. Templates in C++ are a quick and efficient way of achieving polymorphism, an important concept in OOP. It helps us in handling various types of parameters and hence reduces efforts in debugging and testing the code.

Summary

Hope, you can answer all the C++ interview questions. If not, refer our C++ tutorials series and prepare yourself.

Feedback and suggestions are welcomed in the comment section.

Get ready for another set of Interview Questions for C++.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *