Top 50+ C++ Interview Questions and Answers for Job Seekers

Posted in /   /  

Top 50+ C++ Interview Questions and Answers for Job Seekers
vinaykhatri

Vinay Khatri
Last updated on March 19, 2024

    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!

    Top C++ Interview Questions and Answers

    Basic C++ Interview Questions

    1. Why is C++ called so?

    2. What is C++?

    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++?

    C++20 is the latest and the most stable version of C++.

    4. Give some advantages of C++.

    • 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?

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

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

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

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

    <conio.h>

    8. What is a class?

    A class is a user-defined datatype that occupies zero memory until its object isn't created.

    9. How many modifiers does the class have?

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

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

    Private.

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

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

    12. What is inheritance?

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

    13. Define polymorphism.

    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.

    • 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 accessible in OOPs.

    15. Give some disadvantages of OOPS.

    • 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++?

    Call by value

    17. What is recursion?

    A function calling itself is known as recursion.

    18. Define the call by value method.

    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.

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

    20. Define modularity.

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

    Intermediate C++ Interview Questions

    21. What is function overloading?

    It is known as function overloading when more than one function definition is declared with the same function name but different attributes. For example:

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

    22. Define constructors.

    A class member function with 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?

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

    24. What does the malloc() function do?

    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.

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

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

    <stdlib.h>

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

    Encapsulation is one of the properties of object-oriented programming. 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: private , public, and protected . We can limit or release access to class data using these access modifiers. Generally, we put all the class variable data in the private scope so the user cannot 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++?

    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, accelerators, steering wheel, gearboxes, 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?

    Storage classes are the particular keywords in C++ as the prefix to C++ data type . These storage classes can define the variable's lifetime, initial value, and visibility 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?

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

    Friend Class: Friend is a particular keyword that can be used to access a class's private and protected members. 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 A's private and protected members.

    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 consider when defining a friend function or class.

    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 using friend functions.

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

    In function overloading , multiple functions share a similar function name. The function with a similar 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 parent class method in the child class. It can be achieved at the runtime, meaning 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?

    The main() function is essential 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++?

    The following table enumerates the 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, 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?

    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.

    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.

    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 structure's members 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?

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

    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, ensuring 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?

    No. It does not matter how the derived class inherits the base class; private members of the base class can not be accessed 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;
    }

    Output

    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.

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

    Program

    #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++?

    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 helpful 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++.

    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++?

    No. In C++ string , It is defined as an array of characters, which makes it a non-primitive data type. However, each string character 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?

    We can not perform destructor overloading in C++ classes because destructor methods neither accept any argument nor return any value. Therefore, there is no possibility of overloading destructors in C++.

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

    The concept of namespace was introduced in C++ and was missing in C. Namespace is generally used to resolve the conflict between two variables having similar names. With the help of a namespace, we can declare various identifiers or variables with the same name for different values and 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++?

    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++?

    Tokens can be defined as names or minor 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; 
    } 

    Output

    TechGeekBuzz.com

    51. Write a C++ function "sum" that calculates the sum of two numbers without using the + operator.

    #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 essential programming domains and concepts, making it an ideal programming language for beginners.

    It covers essential topics, such as arrays, structures, and dynamic and static binding, that some popular programming languages miss. 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 the best C++ interview questions. During the interview, your coding skills may also be tested apart from your conceptual knowledge. The interviewer may also ask you to write a specific program to solve a problem, so you need to write code as soon as possible without committing 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.

    People are also reading:

    FAQs


    Learn all the concepts of C++, such as data types, variables, object-oriented, file handling, etc. Keep practicing to understand those concepts better and develop mastery of them. Before appearing for an interview, make sure to go through the above list of C++ interview questions to revise all major concepts.

    A C++ developer is in charge of writing and analyzing computer programs written in C++, developing a variety of applications in C++, maintaining and optimizing existing C++ applications, and spotting bottlenecks in applications and fixing them immediately.

    C++ developers should be proficient in C++ programming and object-oriented programming, have knowledge of the latest C++ standards, acquaintance with templating in C++, familiarity with popular libraries, knowledge of embedded system designs, and interpersonal skills, such as management, communication, and willingness to learn.

    The median salary of entry-level C++ developers in India is INR 7.8 lakhs per year, while it is $95K per annum in the United States, according to glassdoor.

    Leave a Comment on this Post

    0 Comments