Signup/Sign In

25 most asked C++ Interview Questions

Posted in Programming   LAST UPDATED: NOVEMBER 10, 2022

    Preparing for an interview? Don't worry. We've got your back. We have created a list of 25 most asked C++ interview questions that you might be asked in your interviews.

    Q01. Differentiate between C and C++.

    • Most C programs run in C++ too. This is because C++ is a superset of C.
    • C supports procedural programming while C++ supports both procedural and object-oriented programming.
    • In C, the main focus is on procedures while in C++, the main feature is on data.
    • C does not support OOP features while C++ does.
    • In C, we perform exception handling by using if-else while in C++, it can be managed well.
    • In C, functions cannot be implemented inside the structures but in C++, they can.
    • C++ follows bottom-up approach while C follows top-down approach.

    Q02. Differentiate between Java and C++.

    • Java does not support pointers while C++ does.
    • Java follows bottom-up approach while C++ follows top-down approach.
    • C++ supports procedural programming while Java supports object-oriented programming.
    • C++ is platform-dependent while Java isn't.
    • C++ supports preprocessors while Java does not.

    Q03. Mention the major features of C++.

    • C++ supports class and objects which makes it more suitable for implementing real-life scenarios.
    • It helps to wrap data and objects together using encapsulation.
    • We can only show required information to the user and hide other details using data abstraction.
    • We can reuse data without having to write the same code again using inheritance.
    • Polymorphism helps us represent data in many forms.
    • It supports message passing and STL.

    Q04. What is STL?

    Standard Template Library (STL) is a library of container templates approved by the ANSI committee to provide programmers with data structures and functions. It is a library of container classes, algorithms, functions and iterators. STL contains

    • Algorithms
    • Containers
    • Functions
    • Iterators

    We have various types of STL container templates suitable for our use according to how we want to store the elements-

    1. Sequence Containers - array, vectors, lists, deque
    2. Container Adaptors - queue, priority_queue, stack
    3. Associative Containers - set, multiset, map, multimap
    4. Unordered Associative Containers - unordered_set, unordered_multiset, unordered_map, unordered_multimap

    Q05. What do you mean by OOPS?

    Object Oriented Programming tends to bind together data and functions such that the data is secure and cannot be accessed by other functions. It implements real-world entities using the concepts of inheritance, data abstraction, encapsulation, polymorphism, etc.

    OOPS is implemented using classes and objects. Class is a user-defined data-type which has data members and member functions. Object is an identifiable entity with its own characteristics and behaviour.

    Encapsulation is defined as wrapping up of data and information under a single unit. Encapsulation leads to data abstraction or hiding. For example, several departments are put together to form an organization.

    Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. For example, we don't know the salaries of our teachers. That information is hidden from us.

    The ability of a message to be displayed in more than one form is called polymorphism. We can have a sum function to add two integers and a function with the same name to add three integers.

    The capability of a class to derive properties and characteristics from another class is called Inheritance. Pencil class is derived from the class Stationery.

    Dynamic Binding is implemented using virtual functions. Here, the code to be executed in response to function call is decided at runtime.

    Q06. What do you mean by class and object?

    Class is a user-defined data-type which has data members and member functions. Object is an identifiable entity with its own characteristics and behaviour. They together help us implement OOP in C++. We use object to access class members. We can say that object is an instance of a class.

    When a class is defined, it is not allocated memory. It is done only after the creation of an object.

    Q07. What are the differences between references and pointers?

    • Pointers don't need to be initialized but references do.
    • Once we have created a pointer and made it point to some location, we can make it point to some other location. We cannot do this with references.
    • Pointers can be NULL but references cannot.
    • We dereference a pointer to access value at the location to which it is pointing but we don't need to do so with references. It can be used directly.

    Q08. What are access specifiers in C++?

    Access specifiers are used to define how the functions and variables can be accessed outside the class. They are of three types-

    • Private: Private members can be accessed only within the same class. They cannot be accessed outside the class they are declared.
    • Public: Public members can be accessed from anywhere.
    • Protected: Protected members cannot be accessed outside the class except in the derived class.

    Q09. What are the differences between malloc() and new and delete and free()?

    • new is faster than malloc() because malloc() is a function while new is an operator.
    • We do not need to to allocate memory with sizeof() using new but we have to do so in malloc().
    • new returns the exact data type, while malloc() returns void *.
    • new calls constuctors while malloc() doesn't.
    • new initializes new memory to 0 while malloc() does so with garbage value.
    • free() is used on memory allocated by malloc( ) or calloc( ) in C while delete is used on memory allocated by new in C++.

    Q10. Structure vs Class

    • Structure and class both are user-defined data types but the variables in structure are stored in stack memory while those of class are stored in heap memory.
    • We can initialize class members directly but not structure members.
    • We use struct keyword to define a structure while class is defined by class keyword.
    • Class supports inheritance while structure does not.
    • Members of a class are private by default while members of struct are by default public.

    Q11. What are inline functions?

    Inline function is a function in which the whole code is substituted at the point of function call. This reduces overhead, increases efficiency and makes compiling faster. They are beneficial when the code of the inline function is small and simple. It is completely on the compiler whether it considers it as inline or not.

    inline return-type function-name(parameters) {

    // function body

    }

    Q12. What is friend function and class?

    Friend function is not a member of the call but can access the private and protected members of the class. It is included in the class definition.

    It cannot be called by object of the class. It must be invoked like a normal function. A friend function cannot be inherited.

    A friend class can access private and protected members of the classes of which it is a friend(declared in those classes).

    Java does not support friendship.

    Q13. Explain the types of overloading. Also, name the operators that cannot be overloaded.

    When two or more functions have the same name but a different parameter list, it is called function overloading. We cannot overload functions with different return types.

    In operator overloading, an operator is overloaded to provide a user-defined definition to it. For example, we can overload an operator ‘+’ in a class like String to concatenate two strings by just using +.

    Some operators which cannot be overloaded are-

    • Scope Resolution Operator (::)
    • Conditional Operator (?:)
    • Member Access or Dot operator (.)
    • Pointer-to-member Operator (.*)
    • Size Operator (sizeof)

    Q14. What are virtual functions. Explain with an example.

    A virtual function is a function is declared within a base class which is overridden by a derived class. It is used to implement runtime polymorphism. It cannot be static and should be accessed using pointer or reference of base class type.

    #include<iostream>
    using namespace std;
      
    class base {
    public:
        virtual void print()
        {
            cout<<"Base class print()\n";
        }
    };
      
    class derived : public base {
    public:
        void print()
        {
            cout<<"Derived class print()\n";
        }
    };
      
    int main()
    {
        base *bptr;
        derived dobj;
        bptr = &dobj;
        bptr -> print();
        return 0;
    }


    Derived class print()

    Q15. What is this pointer?

    Each object in C++ can have access to its own address through this pointer. It is an implicit parameter to all member functions and is available as a local variable within all nonstatic functions. It used to refer to the invoking object in a member function. Friend functions do not have a 'this' pointer.

    Q16. What are VTABLE and VPTR?

    vtable is a table of function pointers and vptr is a pointer to vtable. vtable is maintained per class while vptr is maintained per object.
    The compiler adds additional code in every constructor and polymorphic function to maintain and use vtable and vptr.
    Every class that uses virtual functions or is derived from a class that uses virtual functions has it's own virtual table as a secret data member set up by the compiler during compile time.
    The vpt, is a hidden pointer added by the ompiler to the base class. It points to the virtual table of that particular class. It is inherited to all the derived classes.

    Q17. What are the different types of inheritance?

    • Single Inheritance: A class inherits from only one class.
    class A
    { 
        //function body
    };
    
    class B: public A
    {
        //function body
    };
    • Multiple Inheritance: A class can inherit from more than one class.
    class B
    { 
        //function body
    };
    class C
    {
        //function body
    };
    class A: public B, public C
    {
        //function body
    };
    • Multilevel Inheritance: A derived class inherits another derived class.
    class C
    { 
        //function body
    };
    class B:public C
    {
        //function body
    };
    class A: public B
    {
        //function body
    };
    • Hierarchical Inheritance: More than one subclass is inherited from a single base class.
    class A  
    {  
        //function body  
    }    
    class B : public A   
    {  
        //function body 
    }  
    class C : public A  
    {  
        //function body 
    }   
    class D : public A  
    {  
        //function body.  
    }   

    Q18. What are the types of polymorphism in C++? Explain with code.

    It is of two types-

    • Runtime polymorphism is also known as dynamic polymorphism. It is implemented at run-time. We implement function overriding using runtime polymorphism. Function overriding means when the child class contains the method which is already present in the parent class, the child class overrides the method of the parent class. The function should be same with different definition.
    #include<iostream>
    using namespace std;
      
    class base {
    public:
        virtual void print()
        {
            cout<<"Base class print()\n";
        }
    };
      
    class derived : public base {
    public:
        void print()
        {
            cout<<"Derived class print()\n";
        }
    };
      
    int main()
    {
        base *bptr;
        derived dobj;
        bptr = &dobj;
        bptr -> print();
        return 0;
    }


    Derived class print()

    • Compile-time polymorphism is also known as static polymorphism. It is implemented at the compile time. Function overloading is an example of compile-time polymorphism.
    #include <iostream>  
    using namespace std;  
    class Add  
    {  
       public:  
       int sum(int a, int b)  
       {  
           return(a + b);  
       }  
       int sum(int a, int b, int c)  
       {  
           return(a + b + c);  
       }  
    };  
    int main()  
    {  
        Add ad;  
        int res1,res2;  
        res1 = ad.sum(2, 3);  
        res2 = ad.sum(2, 3, 4);  
        cout<<res1<<"\n"<<res2;  
        return 0;  
    }  

    Q19. Mentions the types of constructors in C++. What are destructors? Can destructors be virtual?

    Constructor is generally used for initialization. They do not have a return type.

    • Default constructor is the constructor which doesn’t take any argument. It has no parameters. It is created by default in each class.
    • Parameterized Constructors take arguments to initialize an object when it is created. We use the parameters to initialize the object. When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor.
    • Copy constructor initializes an object using another object of the same class.

    Destructor are member function which destroy the objects created by the constructor. We use a tilde(~) symbol before their name.

    Yes, they can. A virtual destructor is used in the base class to destroy the derived class object. It is declared by using the ~ tilde symbol and then virtual keyword before the name.

    Q20. What are static members?

    Static members are allocated storage only once in a program and they have a scope till the lifetime of the program. They do not have this pointer and cannot be virtual.

    They are useful to retain the value of variables during the previous function call.

    Q21. What is namespace?

    It is a logical division of the code and defines scope where variables, functions, etc are declared.

    We use it to remove ambiguity so that if two functions exist with the same name, we don't get confused in them.

    C++ consists of a standard namespace, i.e., std which contains inbuilt classes and functions.

    Q22. Does C++ support exception handling?

    Yes, C++ supports exception handling.

    Our code might not execute normally at all times. The malfunctioning of code is called exception.

    When an exception occurs, the compiler tells us that an error has occured. This is called exception handling. In C++, we have three keywords i.e. try, throw and catch which are used in exception handling.

    Q.23 What is the precedence of a global and local variable in a function? If they have the same name, how will you access them?

    Whenever there is a local variable with the same name as that of a global variable, the compiler gives precedence to the local variable.

    In order to access the global variable, we make use of a “scope resolution operator (::)”. Using this operator, we can access the value of the global variable.

    #include<iostream>
    using namespace std;
    int var = 1;
    int main()
    {
     int var = 2;
     cout<<"Global Variable = "<<::var;
     cout<<"\nLocal Variable = "<<var;
    }


    Global Variable = 1
    Local Variable = 2

    Q.24 What is call by value and call by reference? What do you mean by default parameters? How are they used in a function?

    In call by value, only the values of arguments are sent to the function while in call by reference, addresses of arguments are sent. In call by value, when we call a function, a copy of the arguments which are passed is made. Whatever changes we make are done in those copies and does not reflect back on the calling function. In call by reference, we pass the address of variables, so any changes made show in the calling function. To implement call by reference, we use pointers as arguments.

    Q.25 What do you mean by shallow copy and deep copy?

    In shallow copy, if we have two variables, they refer to different areas of memory. When we assign one of them to the other, the two variables refer to the same area of memory. If we modify any of them, changes will be reflected in other.

    In deep copy, when we do the same, the values in the memory area which first one points to are copied into the memory area to which second variable points. If we modify any of them, changes will not be reflected in other.

    We know that C++ is a superset of C. In order to not miss anything and do your best, don't forget to check out top 25 C interview questions here.

    About the author:
    Aditi Verma is a skilled author and content creator with expertise in programming languages such as C and C++, as well as Data Structure and DBMS. With an educational background in Computer Science, Aditi's writing is both informative and engaging.
    Tags:interview-questionscpp
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS