C++ Interview Questions and Answers

In this tutorial, we are going to discuss C++ Interview questions and Answers which will help you to prepare better for interviews and placements. This will also help you to build your basic knowledge of C++ programming language. Let’s start!!!

Basic Interview Questions on C++ Programming Language

Q.1 Write a program to check for equality without using arithmetic and comparison operators?
Ans.

#include<iostream>
using namespace std;
int main(){
   int a = 16;
   int b = 13;
   if ( (a ^ b) )
  	cout<<"a is not equal to b";
   else
  	cout<<"a is equal to b";
  	return 0;
}

Output-
a is not equal to b

Q.2 What is the output of the following program?

main()
 {
extern int i;
 cout<<i<<endl;
 }
int i=20;

Ans. 20

Q.3 What is the output of the following program?

#include <iostream>
using namespace std;
int foo(unsigned int n, unsigned int r) {
  if (n  > 0) return (n%r +  foo (n/r, r ));
  else return 0;
}
int main()
{
int res;
res = foo(22,30);
cout<<res;
return 0;
}

Ans. 22

Q.4 How to allocate a 2d array dynamically in C++?
Ans.

#include <iostream>
int main()
{
  int row = 2, col = 2;
  int* a =  new int[row * col];
   
  int i, j, count = 0;
  for (i = 0; i <  row; i++)
  	for (j = 0; j < col; j++)
     	*(a+ i*col + j) = count++;
   
  for (i = 0; i <  row; i++)
  	for (j = 0; j < col; j++)
     	printf("%d ", *(a + i*col + j));
   
  delete[ ] a;
  return 0;
}

Q.5 Can you write a program to generate random numbers in C++?
Ans.

#include <iostream>
#include <random>
using namespace std;
int main()
{
   int max=15, min=5,i;
   int range = max - min + 1;
   for (i=min; i<max;i++)
  {
    	int num = rand() % range + min;
    	cout<<num;
  }
  return 0;
}

Output:-
It will generate 8 digit random numbers.

Q.6 Why do you use the namespace std in C++?

Ans. A computer needs to know the code for the cout, cin functionalities and it also needs to know which namespace they are defined. But it is not necessary to write namespace, you can simply use scope resolution(::). It works the same as the namespace. Usage of namespace is a bad practice. The problem with putting ‘using namespace’ in the header files of your classes is that it forces anyone who wants to use your classes to also be using those other namespaces.

Q.7 How to remove segmentation faults in C++?

Ans. It basically means that whenever a piece of code tries to perform a read and write operation in a read only location in memory. It indicates an error in memory corruption.
Some reasons and their solutions behind segmentation fault:-

  • Reason:- Accessing an address that is freed.
  • Solution:- Before freeing the pointer, check the assignment or any operation which is required to perform.
  • Reason:- Accessing out of array index bounds.
  • Solution:- Correct the array bound.
  • Reason:- Dereferencing uninitialized pointer
  • Solution:- A pointer must point to valid memory before accessing it.
  • Reason:- Stack Overflow
  • Solution:- Having a base condition to return from the recursive function.

Q.8 How to sort a string using C++?

Ans. You can use the sort() function to sort a string in C++.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main ()
{
  string str;
  cout<<"Enter String"<<endl;
  cin>>str;
  sort(str.begin(),str.end());
  cout<<"Sorted String "<<endl;
  cout<<str;
  return 0;
}

Output:-
Enter String
abdjndod
Sorted String
abdddjno

Q.9 Why is C++ an object oriented programming language?

Ans. C++ always views a problem in terms of objects rather than the procedure of doing it. In object oriented programming, objects represent an entity that can store data and has its interface through functions. The advantages of oop programming is that it makes the program less complex and enhances readability. Components are reusable and extendible. It is also very much desired for maintenance and long term support.

All the member functions of an object may not be used thus it introduces code overhead. If you want to write large business logics and large applications or games then you can make use of the oop programming.

Intermediate Interview Questions on C++ Language

Q.10 How would you implement the Isa and Hasa class relationships?

Ans. A specialized class has Isa relationship with another class. It is best implemented with inheritance. A class may have an instance of another class. For example, an employee ‘has’ a salary, therefore the employee has the ‘HASA’ relationship with the salary class. It is best implemented by setting an object of the Salary class in the Employee class.

There are other relationships also. When one class uses the service of another then it is known as the USESA relationship.

Q.11 Why a template is a better solution than a base class?

Ans. When you design a generic class to contain or manage objects of other types and when the format and the behaviour of the other types are not important to their management then you can use a template rather than using a base class. You can also use templates when those other types are not known to the designer of the container or managed class.

Example:-

#include <iostream>  
using namespace std;  
template<class T> T add(T &i,T &j)  
{  
  T res = i+j;  
  return res;
}  
int main()  
{  
  int x =2;  
  int y =3;  
  cout<<"The value of the addition of is: "<<add(x,y);  
  return 0;  
}

Output:-

The value of the addition of is: 5

Q.12 In C++, how to write to a file?
Ans.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream exp;
exp.open("Tech.txt",ios::out);  
if(!exp)
{
cout<<"File creation failed!";
}
else
{
cout<<"Created a new file!";
exp<<"TechVidvan Tutorial: C++ File Handling!";    
exp.close();
}   
return 0;
}

Output:-

Created a new file!

Name of the file:- Tech.txt
Contents:- TechVidvan Tutorial: C++ File Handling!

In the above example, we created a new file named Tech.txt. We used the stream insertion operator(“<<”) to put data into that file. And the data is “TechVidvan Tutorial: C++ File Handling!”.

Q.13 Instead of reference of the object, can a copy constructor accept an object of the same class as a parameter?

Ans. No, it cannot be done. It will generate an error if you specify a copy constructor with a first argument which is an object and not a reference. This is specified in the definition of the copy constructor itself.

Copy constructor by value:

Syntax :

Tech(const Tech ob)

It will throw you a compile error.

Copy constructor by reference:
Syntax :

Tech(const Tech& ob)

Example:-

class Tech{
public:
    Tech(){}
    Tech(const Tech& ob){
   	 printf("Testing\n");
    }
};

int main()
{
    Tech ob1;
    Tech ob2=ob1;
    return 0;
}

Q.14 If a constructor fails, how can you handle it?

Ans. You can throw an exception to handle the failure of a constructor. Constructor don’t have a return type. That’s why it is not possible to use return types. All you can do to handle the failure of a constructor is to throw an exception.

You should use exceptions to signal failure in constructors. The memory related with the object is cleaned up if the constructor finishes by throwing an exception.

void fun()
{
  A a;
  B* p = new B();  
}

If A:A() throws an error then the memory for x will not leak. And if B:B() throws an error then the memory for *p will not leak.

Q.15 State the difference between a copy constructor and an overloaded assignment operator?

Ans. An overloaded assignment operator helps you to assign the contents of an existing object to another existing object of the same class.

A copy constructor helps you to construct a new object by using the content of the argument object. It is called when an object is passed by value. Copy constructor is itself a function. You can also perform a user-defined copy constructor.

Q.16 Can you call a destructor explicitly on a local variable?

Ans. No, you cannot call a destructor explicitly on a local variable. It will be called again at the close } of the block in which the local is created. It happens automatically. And there is no way to stop it from occurring.
You will get some bad results if you call a destructor on the same object.

void Example(){
Fred a;
 Fred b;
 // ...
}

In the above example, the destructor of b will be executed first then the destructor of a will be executed.

Q.17 Why should you use the “placement_new”?

Ans. There are many types of placement_new. Though a simple way to use this is to place an object at a particular location in memory. It can be done by supplying the place as a pointer parameter to the new part of a new expression.

include // Must #include this to use "placement new"
#include "Fred.h"
void func()
{
char mem[sizeof(Fred)];
void* place = memory;
Fred* f = new(place) Fred();

}

NOTE:- Use it only when you really care that an object is placed at a particular location in memory. You have to take full responsibility that the pointer which you passed to the “placement_new” operator points to a region of memory that is big enough.

Q.18 State the difference between List x; and List x();?

Ans. There is a big difference between these two. Let’s say that List is the name of the same class. The function func() declares a local list object called x:

void func()
{
List x; // Local object named x 
}
void fun()
{
List x(); // Function named x 
...
}

In the above example, the func() function declares a local List object called x. And, the function fun() declares a function named x() that returns a List. So, a function within another function.

Q.19 What will happen when you create and destroy a derived-class object?

Ans. The constructor of the base class is called to initialize the data members inherited from the base class. The constructor of the derived class is called to initialize the data members which are added in the derived class. It is then reusable.

When the object is destroyed then the destructor of the derived class is called on the object first. Then the destructor of the base class is called on the object.

At last, the allocated space is reused for the full object. Space is allocated on the stack or heap for the full object.

Q.20 Why should you use new instead of malloc()?

Ans. Constructor and Destructors:- Unlike malloc(sizeof(Anything)), new Anything() calls Anything’s constructor. Also delete p calls the destructor of *p.

Type Safety:- malloc() returns a void* which is not type safe. new returns a pointer of the right type.
Overridability:- The class can override the new operator. And malloc() is not overridable.

Q.21 How to allocate or deallocate an array of things?
Ans.

Use p = new T[n] and delete[] p:

Anything* p = new Anything[100];
…
delete[] p;

So, when you allocate an array of objects using new, you must use [] in the delete statement. It is useful to differentiate between a pointer to a thing and a pointer to an array of things.

Q.22 Can you tell what a dangling pointer is?

Ans. It takes place when you use the address of an object after its lifetime is over. It can happen in situations such as returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

This is the most common bug that is related to pointers and memory management. It is also known as wild pointers.
You can avoid the errors caused by the dangling pointer by initializing the pointer to the NULL value.

Example:-

#include <stdio.h>  
int *f()  
{  
static int x=10;  
return &b;  
}  
int main()  
{  
int *ptr=f();  
printf("%d", *ptr);  
return 0;  
} 

Q.23 Write a program to check if the word is palindrome or not!
Ans.

#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char s1[20]="nun", s2[20];
int i, j, len = 0, flag = 0;
len = strlen(s1) - 1;
for (i = len, j = 0; i >= 0 ; i--, j++)
s2[j] = s1[i];
if (strcmp(s1, s2))
flag = 1;
cout << "The word is: " << s1<<endl;
if (flag == 1)
cout << "It is not a palindrome!";
else
cout  << "It is a palindrome!";
return 0;
}

Output:-
The word is: nun
It is a palindrome!

Advance Interview Questions on C++

Q.24 How to create a thread using C++ programming language?
Ans.

#include <iostream>
#include <pthread.h>
using namespace std;

char* st = "Child thread";

void* fun(void *st)
{
  cout << "Created child thread: " << (char*)st;
}
int main()
{
  pthread_t t;    
  pthread_create(&t, NULL, &fun, (void*)st);
  cout << "Created Main thread!" << endl;
  pthread_join(t, NULL);
  exit(EXIT_SUCCESS);
  return 0;
}

Output:
Created Main thread!
Created child thread: Child thread

Q.25 State the difference between object oriented programming and procedural programming.
Ans.

Procedural Programming Object Oriented Programming
In Procedural programming, there is no data security. Object oriented programming provides data security by using access specifiers and it is more secure and efficient.
In procedural programming, the program is divided into functions. The program is divided into small blocks called objects in object oriented programming.
It works on the top-down approach. It works on the bottom-up approach.
C supports procedural programming. C++ supports object oriented programming.
Function is more important than data. Here, data is more important than functions.
It is based on an unreal world. It is based on the real world.

Q.26 Can you predict the output of the following program?

#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char let = 'T', new_let;
int val = 20, res;
if(islower(let))
new_let = toupper(let);
else
new_let = val + let;
res = new_let + 21;
cout << res <<endl;
return 0;
}

Ans. 125

Q.27 Write an algorithm to reverse a linked list.
Ans.

template
void linkt::reversing()
{
node ptr= head;
node nextp= ptr->_next;
while(nextp)
{
node tmp = nextp->_next;
nextp->_next = ptr;
ptr = nextp;
nextp = tmp;
}
head->_next = 0;
head = ptr;
}

Q.28 Can you tell me your way of debugging when you came across a problem?
Ans. You can debug with amazing tools like:-

  • GDB, DBG, Visual Studio.
  • You can make use of tusc to trace the last system call before crashing.
  • Analyzing the core dump
  • It is very helpful to put debug statements in the program code.
  • Proofreading your code carefully.

Q.29 Can you find the error in the following code?

int main()
{
const int data = 230;
const int *const ptr = &data;
(*ptr)++;
int value = 20;
ptr = &value;
}

Ans. It is not possible to change the value of a constant variable through the entire code. The statements ‘(*ptr)++’ and ‘ptr=&value’ cannot modify a constant object as well.

Q.30 In C++, which operators can or cannot be overloaded?

Ans. In C++, we can overload most of the operators except :: and .*. Below is an example of a subscript operator which returns a reference.

Without operator overloading:-

class Arr{
public:
int& data(unsigned i) { if (i > 99) error(); return val[i]; }
private:
int val[100];
};

int main()
{
Arr a;
a.data(15) = 35;
a.data(11) += a.data(12);
...
} 

Same one with Operator Overloading:-

class Arr{
public:
int& operator[] (unsigned i) { if (i > 99) error(); return value[i]; }
private:
int value[100]; };

int main()
{
Arr a;
a[15] = 35;
a[11] += a[12];
...
}

Q.31 Can you guess the output of the following program code?

#include <iostream>
using namespace std;
int main()
{
int positive = -2;
try
{
if (positive < 0)
{
throw "It must be a positive number!";
}
cout << positive;
}
catch(const char *msg)
{
cout << "error: " << msg;
}
return 0;
}

Ans. error: It must be a positive number!

Q.32 What will be the output of the following program?

#include <iostream>
#include <string>
using namespace std;
template<typename Tech>
void display(Tech out)
{
cout << out << endl;
}
int main()
{
string s("Have a nice day!");
display(s);
return 0;
}

Ans. Have a nice day!

Q.33 What will be the output of the following program?

#include <iostream>
using namespace std;
class Tech
{
int t;
public:
virtual void print() = 0;
};
class Random: public Tech
{
public:
void print(){
cout<<"Random Class"<<endl;
}    
};
int main()
{
Tech t;
a.print();
return 0;
}

Ans. The above program will give you an error because C++ does not allow you to declare a normal object for an abstract class.

Q.34 What will be the output of the following program code?

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    bitset<8> out(200);
    cout<<out.any();
}

Ans. 1

Q.35 Can you guess the output of the following program code?

#include <iostream>
using namespace std;
int main(){
int num, val = 3;
num = (100 % val ? val + 1 : val - 1);
cout << num <<  endl;
return 0;
}

Ans. 4

Summary

In this tutorial, we discussed some advanced interview or job level questions of the C++ programming language and we also gave their answers. These questions will help you to prepare better for the interview.