Top 25 C++ Interview Questions

By | October 30, 2020
C++ Interview Questions

C++ is one of the best picks to start the programming journey, and many professional suggests to it learn before moving to any other high-level programming language. C++ cover all the basic domains and concepts of programming world which makes it ideal programming language for beginners. It even covers all the major topics such as arrays, structures, dynamic and static binding, which are still missing in some popular programming languages. However, with time C++ is being obsolete, but still, many companies use it to build applications and operating systems. Performance and closeness to system hardware are the two main assets of C++ which are still helping it to stand with other popular languages which offer much more than C++. Still, if you google for C++ Jobs you will find many posted jobs with a good salary. Here we some most frequent C ++ Interview questions.

Vamware

Here we have picked some of the C++ Interview Questions which are often asked during the interviews, have a look at these and make sure that you try to understand all.

Top C++ Interview Questions

Here we have listed a lot of C++ Interview Questions which are asked in the interview:

Question: What C++ signify?
Answer: C++ was first introduced in 1979 at Bell Labs. It got its name after Programming Language C, we can say that C++ is the increment Version of C having OOP’s concepts. The ++ sign of C++ itself signifies the increment of C.

Question: What is C++?
Answer: C++ is a High-level Programming language, created back in 1979 by Bjarne Stroustrup, and released in 1985. C++ is basically used for developing desktop applications or software.

Question: Give some advantages of C++.
Answer: 

  • It’s a highly portable programming language.
  • It supports the concept of OOP’s such as class, inheritance polymorphism, etc.
  • The security of the original code.
  • Easy to install

Question: What is a Pointer?
Answer: In C++ a pointer is a variable that holds the memory address of another variable in memory.

Question: What header file do in C++?
Answer: Header files tell the compiler how to call some functionality.

Question: What is the header file of getch() in C++?
Answer: <conio.h>

Question: What is a class?
Answer: A class is a user-defined datatype, which occupies zero memory until its object not created.

Question: How many modifiers does class have?
Answer: A-Class has 3 modifiers Private, Public and Protected.

Question: What is by default modifier of the class if any modifier is not defined?
Answer: Private

Question: Name the various OOPS concept of C++.

  • Class
  • Objects
  • Polymorphism
  • Inheritance
  • Data binding
  • Abstraction
  • Encapsulation

Question: What is inheritance?
Answer: Inheritance is a concept of OOPs by virtue of it a derived class can inherit the properties and method of the base class.

Question: Define polymorphism.
Answer: Polymorphism is defined as the property of classes having the same method name but shows different functionality when calling with a different object.

Question: Give some Advantages of OOPS

  • It makes the reuse of code very easy.
  • Ease of Comprehension
  • Easy to maintain and understand the code.
  • Easy to redesigned the code.

Question: Give some disadvantages of OOPS.
Answer: 

  • OOPS, coding is tricky.
  • Need proper planning and designing to make an OOPS program.

Question: What is the default function call method in C++?
Answer: Call by value.

Question: What is recursion?
Answer: Function calling itself is known as recursion.

Question: Define call by value method.
Answer: In call by value, the copy of the actual parameter sends to the function and all the changes occur on the copies, the actual parameter remains the same.

Question: Define the call by the reference method.
Answer: In call by reference method the actual parameters send to the function and all the changes occur on the parameter reflects back on the actual parameters.

Question: Define Modularity.
Answer: To partitioning of the program into individual components is called Modularity.

Question: What is a function Overloading?
Answer: When several function definitions are declared with the same function name and different attributes is known as function overloading.

e.g.

float divide(int a, int b);
float divide(float x, float y);

Question: Define constructors.
Answer: A member function of the class having the same as the class that automatically called when the object is created is known as a constructor.

e.g.
class Teacher
{
private:
int salary;
public:
Teacher()
{
Salary=1000;
}
};

Question: What is a parameterized constructor?
Answer: Constructor which accept some parameters to the invocation is known as parameterized constructors.

Question: What malloc() function do?
Answer: Malloc() function provide a dynamic memory location to a variable during the run time.

Question: Give an example of the copy constructor.
Answer: 

class cop
   {
     //class cop body
   }
Cop C1 // default constructor
Cop C2 = C1 // Copy Constructor

Question: What is the header file of the function abs()?

Answer: #include<stdlib.h>

Question: What do you know about Encapsulation in C++?

Answer: Encapsulation is one of the Object-Oriented Programming properties, and it is used to wrap up the various data elements and methods(functions) in a single unit called class.  The main objective of encapsulation is to prevent direct access to class data variables.

How encapsulation achieved in C++ classes:

  •  In C++ we have 3 access modifiers private, public and protected, and using these access modifiers we can limit or release the access of class data. Generally, we put all the class variable data in private scope so the user could not directly access them.
  • Instead of giving direct access to variable data for modification, we can create different getter and setter methods for doing the same tasks.

Example:

#include<iostream> 
using namespace std; 
  
class Encap
{ 
    private: 
        // Hide data to prevent direct access
        int num=0; 
          
    public: 
        // function to increase the value of num  
        void increase(int a) 
        { 
            num =num+a; 
        } 
          
        // function to decrease the value of num
        void decrease(int a) 
        { 
            num=num-a; 
        } 
        
        //show the value of num
        void show()
        {
        	cout<<num;
		}
}; 
  
int main() 
{ 
    Encap obj;
    obj.increase(5);   
    obj.show(); 
    return 0; 
}

Output:

5

Question: What do you know about Data Abstraction in C++?

Answer: Data Abstraction can only be achieved via Data Encapsulations. In Data Abstraction we try to hide the internal working of methods and only provide essential access to the user.

Let’s take a real-world example of Car, in a car we have breaks, accelerator, steering wheel, gearbox, etc which can be directly accessed by the driver, here the driver does not need to care about the internal working of all the car elements, and still, he can use all the car features.

How to achieve Data Abstraction in C++:

  • Using class.
  • Using Header Files.
#include <iostream>    
using namespace std;    
 class Cal    
{    
    private: int a, b,res; // private variables    
    public:    
    void mul()     
    {    
        cout<<"Enter two numbers for multiplication: ";    
        cin>>a>>b;    
        res= a*b;    
        cout<<"Multiplication of two number is: "<<res<<endl;   
    }    

    void div()    
    {    
        cout<<"Enter two numbers for Division: ";    
        cin>>a>>b;    
        res= a/b;    
        cout<<"Division of two number is: "<<res<<endl;   
    }    
};    
int main()    
{    
    Cal c;    
    c.mul();
    c.div();    
    return 0;    
}    //Here we achived abstration using class.

Question: What do you know about C++ storage class?

Answer: Storage classes are the special keywords reserved in C++ as the prefix to C++ data type. These storage classes can define the lifetime, initial value and visibility of the variable throughout the program.

In C++ we have 5 storage classes:

  1. auto
  2. register
  3. extern
  4. static
  5. mutable
Storage Class Specifier Keyword Storage Default Value Scope Life
Automatic auto RAM Garbage Local (Limited to the block) Limited to the block execution
Register register Register Garbage Local (Limited to the block) Limited to the block execution
Static static RAM 0 Local (Limited to the block) Throughout the complete program
External extern RAM 0 Global Throughout the complete program
mutable mutable Ram garbage Local (Limited to the block) Class

Example:

#include <iostream> 
using namespace std; 
int e;
int main() 
{ 
auto int a;
register int r;
extern int e;
static int s;

cout<<"Auto a= "<<a<<endl;
cout<<"register r= "<<r<<endl;
cout<<"extern e= "<<e<<endl;
cout<<"static s= "<<s<<endl;
return 0; 
}

Output:

Auto a= 0
register r= 1
extern e= 0
static s= 0

Question: What do you know about Friend class and Friend function?

Answer: The concept of Friend in C++ challenges the Data Encapsulation and abstraction properties of OOPs in C++.

Friend Class: Friend is a special keyword, which can be used to access the private and protected members of a Class. Suppose if there are two classes A and B, B is the Friend class of A then B will be able to access all the private and protected members of A.

Example:

#include<iostream>
using namespace std;    

class A 
{
	private:
		int data=100;
	public:
		friend class B;
};

class B
{
	public:
		//a is the object of A
		void access(A& a)
		{	//in B class we can access A's private values
			cout<<"A's data is "<<a.data;
		}
		
};
int main()
{
	A a;
	B b;
	b.access(a);
	return 0;
}

Output:

A's data is 100

Friend Function: The concept of Friend function is similar to friend class, but here instead of giving complete access over Private members to a class, we grant it to some specific functions.

Example:

#include     
using namespace std;    

class A 
{
	private:
		int data=100;
	public:
		friend void access(A&);  
};

// this function can access A's data 
void access(A& a)
{
	cout<<"The value of A data is "<< a.data;
}

int main()
{
	A a;
	access(a);
	return 0;
}

Output:

The value of A data is 100

Question: List the major points we need to care about when we define a friend function or class.

Answer: Here are the major points about friend functions and class.

  • We should always use a limited number of Friend classes and functions. The more friends we defined in a class the more we compromise with class data security.
  • There is no mutual friendship between two friend classes, which means, if B is the friend class of A, then A does not become the friend class of B.
  • Friend property can not be inherited using inheritance class.
  • Instead of Friend class, we should prioritize the use of friend functions

Question: What is the difference between function overloading and function overriding?

Answer: Function Overloading:

  • In function overloading, multiple functions share a similar function name.
  • The function with similar function name must have a different number or Data type of parameters.
  •  It can be achieved at Compile time.

Example:

#include<iostream>
using namespace std;    

//function add with 2 parameters
void add(int a, int b)
{
	cout<<"The sum of 2 number is: "<<a+b<<endl;
}

funciton add with 3 parameters
void add(int a, int b, int c)
{
	cout<<"The sum of 3 number is: "<<a+b+c<<endl;
}
int main()
{
	add(3,4);
	add(3,4,5);
	return 0;
}

Output:

The sum of 2 number is: 7
The sum of 3 number is: 12

Function Overriding:

  • In function overriding we refined the method of parent class in child class.
  • It can be achieved at runtime, which means at runtime compiler decide which method to execute.

Example:

#include<iostream>
using namespace std;    
class Parent
{
	public:
	void show()
	{
		cout<<"It's in the Parent class";
	}
};

class Child : public Parent
{
	public:
	// overriding the base show() method
	void show()
	{
		cout<<"It's the Child class";
		}	
 };
int main() 
{ 
	Child c;
	c.show();
}

Output:

It's the Child class

Question: What happens if there is no main() function in a C++ program?

Answer: The main() function is important for code execution because it contains the flow of code. If there is no main() function in a C++ program then the code will not be executed, however, there will be a code compilation process, but no execution.

Question: Can you compare Java and C++?

Answer:

C++ Java
In C++ we have destructor which can be used manually to destroy the class object. In Java, we do not have the manual control over Java objects, but here we have automatic garbage collector, which is an alternate for destructor.
In C++ we have multiple inheritance, operator overloading, pointers, and structure. All these features are missing in Java
C++ standard does not have inbuilt support for threads. Java comes with an inbuilt thread class.
C++ code can be compiled using C++ compiler, and the operating system executes the byte code. Java compiler also compiles down the Java Source code into byte code, but it requires a Java Virtual Machine (JVM) to execute the Byte code.

Question: How C++ is different from C.

Answer: 

C C++
C is limited to procedural programming. C++ support procedural as well as object-oriented programming.
C does not support function overloading, inheritance, template and virtual functions. All these features are available in C++.
In C we have to mention the data type specifier when we print any result. In C++ we do not need to mention the data type specifier.
C does not support direct exception handling. In C++ we have special keywords like try, except, and throw for exception handling.

Question: Explain how Virtual functions related to runtime polymorphism?

Answer: In C++ runtime polymorphism can be achieved using virtual functions. A virtual function is declared using virtual keyword in the base class and redefined in the child class. The main objective of virtual function to resolve the function calling problem which is done during run time.

Example:

#include<iostream>
using namespace std; 
  
class Parent { 
public: 
    virtual void show() 
    { 
        cout << "Its the show() method of parent class " << endl; 
    } 
  void another()
  {
  	cout<<"Its another parent class function"<<endl;
  }
}; 
  
class Child : public Parent { 
public: 
	//redefing the parent virtual function
    void show() 
    { 
        cout << "It's the Child class show" << endl; 
    } 
    //overriding the base class another funciton
    void another()
    {
    	cout<<"It's another function of Child class"<<endl; } }; 
int main() 
{ 
Parent* p_ptr; 
Child c; 
p_ptr = &c;

// dynamic_binding, it will call the Child class show method 
p_ptr->show();

//static_binding, it will call the parent class anothr method
p_ptr->another();
}

Output:

It's the Child class show
Its another parent class function

Question: Mention some difference between C++ structure and class.

Answer: C++ structure and class can be used to perform some similar task, but they have some differences.

  • If we do not mention any specifier then by default the members of the structure become public, but in Class members become private.
  • Class provide more security over the structure.
  • The class have unique methods(constructor and destructor) which invoke automatically, whereas structure does not provide any such methods.
  • One class can inherit the property of another, whereas Structure can not.

Question: What do you know about static keyword?

Answer: It is a special keyword which could be used with variables, function, class objects, etc. and it allocates a lifetime memory storage to the specified data object.

Static keyword can be used with:

  •  Class objects
  • Class methods
  • Variables
  • Functions

Question: Explain the various access specific present in C++.

Answer: In C++ access specifier limit the scope and accessibility of the Class data members and methods. In C++ we have 3 access specifiers.

  • Private
  • Public
  • Protected

Private:

It is the default access specifier, and it makes sure that no outsider could access the class data members.

Public:

If the data members and methods are specified under public access specifier then all those members can be accessed through the class object.

Protected:

It is a combination of Public and private specifier. If the members of a class are under-protected access specifier then they behave like public members for the class which inherit it but act as a private member for the class object.

Question: If a derived class inherit base class privately, then would the derived call be able to access the private members of the base class?

Answer: No, it does not matter how the derived class inherit the base class, private members of the base class can not be accessed from outside of the class. If a driven class inherit the base class privately then the protected and public members of the base class will fall under the private members of the derived class.

Question: What would be the output of this code?

int main() 
{ 
    int a=0,b;
    b= a++;
    cout<<"a = "<< a<<endl;
    cout<<"b= "<<b<<endl;
	return 0;
}

Answer:

a = 1
b= 0

b= a++; in this statement, the value of a first get used and assigned to b and then modified, which results in b to 0 and increment in a by one.

Question: Write a C++ code and use loop to print this pattern.

* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *

Answer:

#include<iostream>
using namespace std;

int main()
{

    for(int i = 5; i >= 1; --i)
    {
        for(int k = 0; k < 5-i; ++k)
           //for spaces
            cout << "  ";

        for(int j = i; j <= 2*i-1; ++j)
            cout << "* ";

        for(int j = 0; j < i-1; ++j)
            cout << "* ";
        cout << endl;
    }

    return 0;
}

Question: What do you know about abstract classes in C++?

Answer: If a base class consists one or more than one pure virtual function then that class would be considered as a base class. A virtual function would be called a pure virtual function if it does not have any function body and initialized with 0.

The abstract class comes useful when we want a Child class to have a specific method but do not want that method to define in the Parent class.

Example:

#include<iostream>
using namespace std; 

//abstract parent class
class Parent 
{ 
public: 
	//pure virtual function
    virtual void diaper() = 0; 
}; 
  
// This class inherits from Base and implements fun() 
class Child: public Parent 
{ 
    
public: 
    void diaper() { cout << "Put on the diaper"; } 
}; 
  
int main(void) 
{ 
    Child c; 
    c.diaper(); 
    return 0; 
}

Output:

Put on the diaper

Question: Explain the Reference variable in C++?

Answer: A reference variable act as a second name for the existing variable. To define a reference variable we put & symbol before the reference variable name.

Example:

#include<iostream>
using namespace std; 
  
int main(void) 
{ 
	int a= 100;
	
	//ref is the second name for a
	int& ref= a;
	
	// increament in a
	a=a+100;
	
	cout<<"The value of a is ="<<a<<endl;
	cout<<"The value of the reference variable is= "<<ref;
}

Output:

The value of a is =200
The value of the reference variable is= 200

Question: Is string is a primitive data type in C++?

Answer: No, in C++ string is defined as an array of Characters, which make it a non-primitive data type. However, each character of the string can be treated as a primitive data type.

#include<iostream> 
using namespace std;
int main(void) 
{ 
char a[10]="hello";
cout<<a;
}
Output:
hello

Question: Like Constructor overloading can we do destructor overloading?

Answer: No, we can not perform destructor overloading in C++ classes, because destructor methods neither accept any argument nor it return any value so there is no possibility for overloading.

Question: Explain the concept of the namespace in C++.

Answer: The concept of namespace introduced in C++, and it was missing in C. Namespace is generally used to resolve the conflict of two variable having similar names. With the help of namespace, we can declare various identifiers or variables with the same name for different values and different scope and access them according to our need.

#include<iostream>
using namespace std; 
  
// namespace 1
namespace ns_1
{

    int data = 100; 
} 
  
// namespace 2
namespace ns_2
{

    int data = 1000; 
} 
int main() 
{ 
    // Local variable 
    int data = 10; 
    cout<<"Local variable data "<<data<<endl;
    cout << "First namespace ns_1 data "<

Output:

Local variable data 10
First namespace ns_1 data 100
second namespace ns_2 data 1000

Question: What is auto in C++?

Answer: auto is the default class storage assigned to the variable if the developer mentioned no other class storage keyword.

Example;

auto int a=10; is similar to int a=10;

Question: What are tokens in C++?

Answer: Token can be defined as a name or the smallest unit of a program which provide a piece of meaningful information to the compiler.

Here is a list of C++ elements which can be a token:

  • Identifiers
  • Constants
  • Operators
  • String
  • Special symbol
  • keywords

Question: What will be the output of this code?

#include <iostream> 
using namespace std; 

int main() 
{ 
if(cout<<"TechGeekBuzz.com")
return 0; 
} 

Answer: TechGeekBuzz.com

Question: Write a C++ function “sum” that calculates the sum of two numbers without using the + operator.

Answer:

#include <iostream> 
using namespace std; 

int sum(int a, int b)
{
return a-(-b);
}
int main() 
{ 
cout<< sum(10,20);
return 0; 
}

Conclusion:

During the interview apart from your conceptual knowledge, your coding skills may also be tested. The interviewer may also ask you to write a specific program to solve a problem, so there you need to write code as soon as possible without commenting any silly mistakes. We also recommend you, make your data structure and algorithms strong before you appear in the interview because DS and Algo signify the problem-solving capability of the candidate.

If you like this article or have any suggestions, please let us know by commenting down below.

You might also interested in:



											

One thought on “Top 25 C++ Interview Questions

  1. Sana

    I was checking your website and see you have a good design and it looks great, but it’s not ranking on Google and other major search engines.

    Reply

Leave a Reply

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