50 Top C++ Interview Questions and Answers

Posted in /   /  

50 Top C++ Interview Questions and Answers

Vinay Khatri
Last updated on July 12, 2022

    If you Google for C++ jobs, you will find many job openings with decent salaries. Here, we will explain some of the most frequently asked C++ interview questions that will help you to clear an interview and land a job in C++ development. Even if you're not looking for a job in C++, you can go through these interview questions to build a better understanding of the popular programming language.

    So, let's get started!

    Want to master C++ programming from scratch? You can get started here .

    Top C++ Interview Questions and Answers

    Basic C++ Interview Questions/C++ interview questions for freshers

    1. Why is C++ called so?

    Answer: C++ was first introduced in 1979 at Bell Labs. It got its name because it was designed as an extension of the C programming language. Thus, we can say that C++ is the enhanced version of C having OOPs concepts. The ++ sign in C++ signifies extending C.

    2. What is C++?

    Answer: C++ is a high-level programming language. It was created back in 1979 by Bjarne Stroustrup and released in 1985. C++ is mainly used for developing desktop applications and software.

    3. What is the latest version of C++?

    Answer: C++20 is the latest and the stable version of C++.

    4. Give some advantages of C++.

    Answer:

    • It’s a highly portable programming language.
    • It supports the concept of OOPs, such as class, inheritance, and polymorphism.
    • C++ code is highly secure.
    • It is easy to install.

    5. What is a pointer?

    Answer: In C++, pointers are variables that hold the memory addresses of other variables.

    6. What is a header file in C++?

    Answer: Header files tell the C++ compiler to call certain functionalities.

    7. What is the header file of getch() in C++?

    Answer: <conio.h>

    8. What is a class?

    Answer: A class is a user-defined datatype, which occupies zero memory until its object isn't created.

    9. How many modifiers does the class have?

    Answer: A class in C++ can have one of the three modifiers, namely private, public, and protected.

    10. What is the default modifier of a C++ class?

    Answer: Private.

    11. Name the various OOPS concepts of C++.

    Answer:

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

    12. What is inheritance?

    Answer: Inheritance is a concept of OOPs by virtue of which a derived class can inherit the properties and method of its base class.

    13. Define polymorphism.

    Answer: Polymorphism is defined as the property of C++ classes for having the same method offer different functionality when calling different types of objects.

    14. Give some advantages of OOPS.

    Answer:

    • It increases code reusability.
    • Object-oriented programming offers ease of comprehension.
    • It makes it easy to maintain and understand the code.
    • Redesigning the code is also easy in OOPs.

    15. Give some disadvantages of OOPS.

    Answer:

    • OOPS coding is tricky.
    • It requires proper planning and design to make an OOPS program.

    16. What is the default function call method in C++?

    Answer: Call by value .

    17. What is recursion?

    Answer: A function calling itself is known as recursion.

    18. Define the call by value method.

    Answer: In call by value, the copy of the actual parameter is sent to the function, and all the changes occur in the copies. Thus, the actual parameter remains the same.

    19. Define the call by reference method.

    Answer: In the call by reference method, the actual parameters are sent to the function, and all the changes that occur on the parameter reflect back on the actual parameters.

    20. Define modularity.

    Answer: Modularity is the ability to partition a program into individual components.

    Intermediate C++ Interview Questions

    21. What is function overloading?

    Answer: When more than one function definition is declared with the same function name but different attributes, it is known as function overloading. For example:

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

    22. Define constructors.

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

    For example:

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

    23. What is a parameterized constructor?

    Answer: A parameterized constructor is a constructor that accepts some parameters to the invocation.

    24. What does the malloc() function do?

    Answer: The malloc() function is a memory management function. It provides a dynamic memory location to a variable during the run time.

    25. Give an example of the copy constructor.

    Answer:

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

    26. What is the header file of the function abs()?

    Answer: <stdlib.h>

    27. What do you know about encapsulation in C++?

    Answer: Encapsulation is one of the properties of object-oriented programming, and it is used to wrap up the various data elements and methods (functions) in a single unit called a class. The main objective of encapsulation is to prevent direct access to the variables of a class. This is how encapsulation is achieved in C++:

    • In C++, we have three access modifiers, namely private, public, and protected . Using these access modifiers, we can limit or release access to class data. Generally, we put all the class variable data in the private scope so the user could not directly access it.
    • 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

    28. What do you know about data abstraction in C++?

    Answer: Data abstraction can only be achieved via data encapsulation. 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 a car. In a car, we have brakes, accelerator, steering wheel, gearbox, and so on that can be directly accessed by the driver. Here the driver does not need to mull over the internal working of all the car elements like the engine and gear mechanism. Still, she can use all the car features. To achieve data abstraction in C++, we use classes and header files.

    For example:

    #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.

    29. What do you know about the C++ storage class ?

    Answer: Storage classes are the special keywords 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 five 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 Stored in a 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

    Advanced C++ Interview Questions

    30. What do you know about the friend class and friend function?

    Answer: The concept of a friend in C++ challenges the data encapsulation and abstraction properties of OOPs.

    Friend Class: Friend is a special keyword that can be used to access the private and protected members of a class. Suppose there are two classes, say A and B. If 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 the friend function is similar to the 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

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

    Answer: Whenever we define a friend function or class, we need to take care of the following things:

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

    32. What is the difference between function overloading and function overriding?

    Answer: In function overloading , multiple functions share a similar function name. The function with a similar function name must have a different number or datatype of parameters. Functional overloading can be achieved at the 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;
    }
    
    //function 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

    In function overriding, we define the method of the parent class in the child class. It can be achieved at the runtime, which means at runtime, the compiler decides 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

    33. 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 C++ code. If there is no main() function in a C++ program, then the code will not execute. Code compilation will still take place, but there will be no code execution.

    34. Can you compare Java and C++?

    Answer: The following table enumerates the various differences between Java and C++ :

    C++ Java
    In C++, we have a destructor that can be used manually to destroy the class object. In Java, we do not have manual control over Java objects. Instead, here we have automatic garbage collection, which is an alternative for the destructor in C++.
    C++ supports the concepts of multiple inheritances, operator overloading, pointers, and structure. All these features are not available in Java.
    The C++ standard does not have inbuilt support for threads. Java comes with an inbuilt thread class.
    C++ code can be compiled using a C++ compiler, and the operating system executes the byte code. Java compiler also compiles the Java source code into byte code, but it requires a Java Virtual Machine (JVM) to execute the byte code.

    35. How is C++ different from C?

    Answer: The following table highlights the differences between C and C++:

    C C++
    C is limited to procedural programming . C++ supports procedural as well as object-oriented programming paradigms.
    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. C++ has special keywords like try, except, and throw for exception handling.

    36. Explain how virtual functions are related to runtime polymorphism.

    Answer: In C++, runtime polymorphism can be achieved using virtual functions. A virtual function is declared using the virtual keyword in the base class and redefined in the child class. The main objective of the virtual function is to resolve the function calling problem, which occurs during the 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: 
    	//redefining the parent virtual function
        void show() 
        { 
            cout << "It's the Child class show" << endl; 
        } 
        //overriding the base class another function
        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 another method
    p_ptr->another();
    }

    Output:

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

    37. Mention some differences between C++ structure and class.

    Answer: C++ structure and class can be used to perform some similar tasks, but they have the following differences:

    • If we do not mention any specifier, then by default, the members of the structure become public, but in a class, members become private.
    • The class provides more security over the structure.
    • The class has unique methods (constructor and destructor) that are invoked automatically. A structure does not provide any such methods.
    • One class can inherit the property of another class, whereas structures can't do so.

    38. What do you know about the static keyword?

    Answer: It is a special keyword that could be used with variables, functions, objects of a class, and methods of a class. It allocates lifetime memory storage to the specified data object.

    39. Explain the various access specifiers present in C++.

    Answer: In C++, an access specifier limits the scope and accessibility of the class data members and methods. In C++, we have three access specifiers:

    1. Private: It is the default access specifier, and it makes sure that no outsider can access the class data members.
    2. Public: If the data members and methods are specified under the public access specifier, then all those members can be accessed through the class object.
    3. Protected: It is a combination of public and private access specifiers. If the members of a class are under the protected access specifier, then they behave like public members for the class which inherit it but act as private members for the class object.

    40. If a derived class inherits a base class privately, then would the derived class be able to access the private members of the base class?

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

    41. 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 gets used and then assigned to b , and then modified. It results in b storing 0 and increment in a by 1.

    42. Write C++ code and use a 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;
    }

    43. What do you know about abstract classes in C++?

    Answer: If a base class consists of one or more than one pure virtual function, then that class would be considered an abstract class . A virtual function would be called a pure virtual function if it does not have any function body and is initialized with 0. The abstract class comes useful when we want a child class to have a specific method but do not want to define that method 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

    44. Explain the reference variable in C++.

    Answer: A reference variable acts as a second name for an existing variable. To define a reference variable, we put the ampersand (&) 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

    45. Is string a primitive data type in C++?

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

    For example:

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

    46. 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 they return any value. Therefore, there is no possibility of overloading destructors in C++.

    47. Explain the concept of the namespace in C++.

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

    For example:

    #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

    48. What is auto in C++?

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

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

    49. What are tokens in C++?

    Answer: Tokens can be defined as names or the smallest units of a program that provide a piece of meaningful information to the compiler. Here is a list of C++ elements that are tokens:

    • Identifiers
    • Constants
    • Operators
    • Strings
    • Special symbols
    • Keywords

    50. What will be the output of this code?

    #include <iostream> 
    using namespace std; 
    
    int main() 
    { 
    if(cout<<"TechGeekBuzz.com")
    return 0; 
    } 

    Answer:

    TechGeekBuzz.com

    51. 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; 
    }

    Why Learn C++?

    C++ is one of the best languages to start the programming journey, and many professionals recommend learning it before moving to any other high-level programming language. C++ covers all the basic domains and concepts of programming, which makes it an ideal programming language for beginners.

    It covers important topics, such as arrays, structures, and dynamic and static binding, that are missing in some popular programming languages. However, with time, C++ has become obsolete, but still, many companies use it to build applications and operating systems. High performance and closeness to the system hardware are the two main assets of C++, which are still helping it to stand tall among other popular programming languages that offer much more than C++.

    Conclusion

    That's the end of this blog post on best C++ interview questions. 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 committing any silly mistakes.

    We also recommend you develop a strong understanding of data structure and algorithms before you appear for any programming interview because these signify the problem-solving capability of the candidate.

    Wish you all the luck!

    Like these C++ interview questions? Or have any suggestions for us? Please let us know by commenting below.

    For more C++ interview questions designed by experts in the field, you can buy the course here.

    People are also reading:

    Leave a Comment on this Post

    0 Comments