13 Apr 2017

C++ Interview Questions and Answers for Freshers, Experienced


We are providing comprehensive set of C++ Interview Questions and Answers for Freshers and Experienced who wants to get into any industry. It's regardless of which domain or language you would like to pursue your career in, because 90% of campus placement interviews include questions from C or C++. The main reason being a candidate who is fresh out of college is not expected to be a master of widely used languages like Java, Python, Perl etc. and most of the universities have C or C++ as a part of their curriculum. For example, in most institutions C language is being taught along with data structure course and C++ as part of Object oriented programming. So always expect questions on C/C++ in the technical interviews for fresher.

One advantage with fresher interviews is that there are only limited number of concepts and questions and the same has been repeatedly being asked over years. If you want to pursue your career in system level programming like driver development, needless to say, you should show your mastery in C/C++ interviews. Here we have identified and collected a set of frequently asked C++ interview questions and answers for experienced and freshers as well. It's a continuously updated list, go through them, understand the concepts and excel in the interviews.

1. What is difference between C and C++ ?
[This is a usual C or C++ interview question, mostly the first one you will face if you are fresher or appearing for campus interview. When answering this question please make sure you don't give the text book type explanations, instead give examples from real software scenario. Answer for this interview question can include below points, though its not complete list. This question itself can be a 1day interview !!!]

    C++ is Multi-Paradigm ( not pure OOP, supports both procedural and object oriented) while C follows procedural style programming.
    In C data security is less, but in C++ you can use modifiers for your class members to make it inaccessible from outside.
    C follows top-down approach ( solution is created in step by step manner, like each step is processed into details as we proceed ) but C++ follows a bottom-up approach ( where base elements are established first and are linked to make complex solutions ).
    C++ supports function overloading while C does not support it.
    C++ allows use of functions in structures, but C does not permit that.
    C++ supports reference variables ( two variables can point to same memory location ). C does not support this.
    C does not have a built in exception handling framework, though we can emulate it with other mechanism. C++ directly supports exception handling, which makes life of developer easy.

2. What is a class?
[Probably this would be the first question for a Java/c++ technical interview for freshers and sometimes for experienced as well. Try to give examples when you answer this question.]
Class defines a datatype, it's type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.

    class Vehicle
    {
        public:
            int numberOfTyres;
            double engineCapacity;
            void drive(){
                // code to drive the car
            }
    };

3. What is an Object/Instance?
Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below

    Vehicle vehicleObject;

We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.

4. What do you mean by C++ access specifiers ?
[Questions regarding access specifiers are common not just in c++ interview but for other object oriented language interviews as well.]
Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected

    private:
    Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.
    public:
    Members declared as public are accessible from any where.
    protected:
    Members declared as protected can not be accessed from outside the class except a child class. This access specifier has significance in the context of inheritance.

5. What are the basics concepts of OOP?
[ A must OOP / c++ interview question for freshers (some times asked in interviews for 1-2 years experienced also), which everybody answers as well. But the point is, it's not about the answer, but how you apply these OOPs concepts in real life. You should be able to give real life examples for each of these concepts, so prepare yourself with few examples before appearing for the interview. It has seen that even the experienced people get confused when it comes to the difference between basic OOP concepts, especially abstraction and encapsulation.]

    Classes and Objects

Refer Questions 2 and 3 for the concepts about classes and objects

    Encapsulation

Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It's also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data. Consider the below class

    class Person
    {
       private:
          int age;
       public:
          int getAge(){
            return age;
          }
          int setAge(int value){
            if(value > 0){
                age = value;
            }
          }
    };

In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.

    Data abstraction

Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.

    class Stack
    {
        public:
            virtual void push(int)=0;
            virtual int pop()=0;
    };
    
    class MyStack : public Stack
    {
        private:
            int arrayToHoldData[]; //Holds the data from stack
    
        public:
            void push(int) {
                // implement push operation using array
            }
            int pop(){
                // implement pop operation using array
            }
    };

In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.

    Inheritance

Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.

    class SymmetricShape
    {
        public:
            int getSize()
            {
                return size;
            }
            void setSize(int w)
            {
                size = w;
            }
        protected:
            int size;
    };
    
    // Derived class
    class Square: public SymmetricShape
    {
        public:
            int getArea()
            {
                return (size * size);
            }
    };

In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.

6. What is the use of volatile keyword in c++? Give an example.
Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,

    int a = 10;
    while( a == 10){
         // Do something
    }

compiler may think that value of 'a' is not getting changed from the program and replace it with 'while(true)', which will result in an infinite loop. In actual scenario the value of 'a' may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.
In the above example if variable 'a' was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.


7. In how many ways we can initialize an int variable in C++?

In c++, variables can be initialized in two ways, the traditional C++ initialization using "=" operator and second using the constructor notation.

    Traditional C++ initilization

    int i = 10;

variable i will get initialized to 10.

    Using C++ constructor notation

    int i(10);

8. What is implicit conversion/coercion in c++?

Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.

short a = 2000 + 20;

In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.

9. What are C++ inline functions?
C++ inline functions are special functions, for which the compiler replaces the function call with body/definition of function. Inline functions makes the program execute faster than the normal functions, since the overhead involved in saving current state to stack on the function call is avoided. By giving developer the control of making a function as inline, he can further optimize the code based on application logic. But actually, it's the compiler that decides whether to make a function inline or not regardless of it's declaration. Compiler may choose to make a non inline function inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler may ignore. So, please note this point for the interview that, it is upto the compiler to make a function inline or not.

    inline int min(int a, int b)
    {
       return (a < b)? a : b;
    }
    
    int main( )
    {
       cout << "min (20,10): " << min(20,10) << endl;
       cout << "min (0,200): " << min(0,200) << endl;
       cout << "min (100,1010): " << min(100,1010) << endl;
       return 0;
    }

If the complier decides to make the function min as inline, then the above code will internally look as if it was written like

    int main( )
    {
       cout << "min (20,10): " << ((20 < 10)? 20 : 10) << endl;
       cout << "min (0,200): " << ((0 < 200)? 0 : 200) << endl;
       cout << "min (100,1010): " << ((100 < 1010)? 100 : 1010) << endl;
       return 0;
    }

10. What do you mean by translation unit in c++?
We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. In other words, a translation unit consists of

    Contents of source file
    Plus contents of files included directly or indirectly
    Minus source code lines ignored by any conditional pre processing directives ( the lines ignored by #ifdef,#ifndef etc)

11. What do you mean by internal linking and external linking in c++?
[This interview question is related to questions on "translation unit" and "storage classes"]
A symbol is said to be linked internally when it can be accessed only from with-in the scope of a single translation unit. By external linking a symbol can be accessed from other translation units as well. This linkage can be controlled by using static and extern keywords.

12. What do you mean by storage classes?
Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.



13. How many storage classes are available in C++?
Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.
Following storage classes are available in C++

    auto

It's the default storage class for local variables. They can be accessed only from with in the declaration scope. auto variables are allocated at the beginning of enclosing block and deallocated at the end of enclosing block.

    void changeValue(void)
    {
       auto int i = 1 ;
       i++;
       printf ( "%d ", i ) ;
      
    }
    int main()
    {
       changeValue();
       changeValue();
       changeValue();
       changeValue();
       return 0;
    }
    
    Output:-
    2 2 2 2

In the above example, every time the method changeValue is invoked, memory is allocated for i and de allocated at the end of the method. So it's output will be same.

    register

It's similar to auto variables. Difference is that register variables might be stored on the processor register instead of RAM, that means the maximum size of register variable should be the size of CPU register ( like 16bit, 32bit or 64bit). This is normally used for frequently accessed variables like counters, to improve performance. But note that, declaring a variable as register does not mean that they will be stored in the register. It depends on the hardware and implementation.

    int main()
    {
       register int i;
       int array[10] = {0,1,2,3,4,5,6,7,8,9};         
    
       for (i=0;i<10;i++)
       {
          printf("%d ", array[i]);
       }
       return 0;
    }
    
    Output:-
    0 1 2 3 4 5 6 7 8 9

The variable i might be stored on the CPU register and due to which the access of i in the loop will be faster.

    static

A static variable will be kept in existence till the end of the program unlike creating and destroying each time they move into and out of the scope. This helps to maintain their value even if control goes out of the scope. When static is used with global variables, they will have internal linkage, that means it cannot be accessed by other source files. When static is used in case of a class member, it will be shared by all the objects of a class instead of creating separate copies for each object.

    void changeValue(void)
    {
       static int i = 1 ;
       i++;
       printf ( "%d ", i ) ;
      
    }
    
    int main()
    {
       changeValue();
       changeValue();
       changeValue();
       changeValue();
       return 0;
    }
    
    Output:-
    2 3 4 5

Since static variable will be kept in existence till the end of program, variable i will retain it's value across the method invocations.

    extern

extern is used to tell compiler that the symbol is defined in another translation unit (or in a way, source files) and not in the current one. Which means the symbol is linked externally. extern symbols have static storage duration, that is accessible through out the life of program. Since no storage is allocated for extern variable as part of declaration, they cannot be initialized while declaring.

    int x = 10;
    int main( )
    {
       extern int y ;
       printf("x: %d ", x );
       printf("y: %d", y);
       return 0;
    }
    int y = 70 ;
    
    Output:-
    x: 10 y: 70

extern variable is like global variable, it's scope is through out the program. It can be defined anywhere in the c++ program.

    mutable

mutable storage class can be used only on non static non const data a member of a class. Mutable data member of a class can be modified even is it's part of an object which is declared as const.

    class Test
    {
        public:
            Test(): x(1), y(1) {};
            mutable int x;
            int y;
    };
    
    int main()
    {
        const Test object;
        object.x = 123;
        //object.y = 123;
        /*
         * The above line if uncommented, will create compilation error.
         */   
        cout<< "X:"<< object.x << ", Y:" << object.y;
        return 0;
    }
    
    Output:-
    X:123, Y:1

In the above example, we are able to change the value of member variable x though it's part of an object which is declared as const. This is because the variable x is declared as mutable. But if you try to modify the value of member variable y, compiler will throw error.

You can find the summary of c++ storage class specifiers below
C++ Storage Specifier    Storage Location    Scope Of Variable    Life Time
auto     Memory (RAM)     Local     With in function
static     Memory (RAM)     Local     Life time is from when the flow reaches the first declaration to the termination of program.
register     CPU register     Local     With in function
extern     Memory (RAM)     Global     Till the end of main program

14. What is 'Copy Constructor' and when it is called?
This is a frequent c++ interview question. Copy constructor is a special constructor of a class which is used to create copy of an object. Compiler will give a default copy constructor if you don't define one. This implicit constructor will copy all the members of source object to target object.
Implicit copy constructors are not recommended, because if the source object contains pointers they will be copied to target object, and it may cause heap corruption when both the objects with pointers referring to the same location does an update to the memory location. In this case its better to define a custom copy constructor and do a deep copy of the object.

            class SampleClass{
                public:
                    int* ptr;
                    SampleClass();
                    // Copy constructor declaration
                    SampleClass(SampleClass &obj);
            };
    
            SampleClass::SampleClass(){
                ptr = new int();
                *ptr = 5;
            }
    
            // Copy constructor definition
            SampleClass::SampleClass(SampleClass &obj){
                //create a new object for the pointer
                ptr = new int();
                // Now manually assign the value
                *ptr = *(obj.ptr);
                cout<<"Copy constructor...\n";
            }

15. What is realloc() and free()? What is difference between them?

    void* realloc (void* ptr, size_t size)

This function is used to change the size of memory object pointed by address ptr to the size given by size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour may occur depending the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do not match a pointer returned by an malloc(), calloc() or realloc().

    void free (void* ptr)

This function is used to deallocate a block of memory that was allocated using malloc(), calloc() or realloc(). If ptr is null, this function does not doe anything.

16. What is difference between shallow copy and deep copy? Which is default?
[This question can be expected in any interviews, not just c++ interviews. This is a usual question in most of the java interviews.]
When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.

17. What do you mean by persistent and non persistent objects?
[This question may be asked in many ways during c++ interviews, like how to send an object to a remote computer or how to save the your program state across application restarts. All these are related to serialization.]
Persistent objects are the ones which we can be serialized and written to disk, or any other stream. So before stopping your application, you can serialize the object and on restart you can deserialize it. [ Drawing applications usually use serializations.]
Objects that can not be serialized are called non persistent objects. [ Usually database objects are not serialized because connection and session will not be existing when you restart the application. ]

18. Is it possible to get the source code back from binary file?
Technically it is possible to generate the source code from binary. It is called reverse engineering. There are lot of reverse engineering tools available. But, in actual case most of them will not re generate the exact source code back because many information will be lost due to compiler optimization and other interpretations.



19. What are virtual functions and what is its use?
[This is a sure question in not just C++ interviews, but any other OOP language interviews. Virtual functions are the important concepts in any object oriented language, not just from interview perspective. Virtual functions are used to implement run time polymorphism in c++.]
Virtual functions are member functions of class which is declared using keyword 'virtual'. When a base class type reference is initialized using object of sub class type and an overridden method which is declared as virtual is invoked using the base reference, the method in child class object will get invoked.

    class Base
    {
        int a;
        public:
            Base()
            {
                a = 1;
            }
            virtual void method()
            {
                cout << a;
            }
    };
    
    class Child: public Base
    {
        int b;
        public:
            Child()
            {
                b = 2;
            }
            virtual void method()
            {
                cout << b;
            }
    };
    
    int main()
    {
        Base *pBase;
        Child oChild;
        pBase = &oChild;
        pBase->method();
        return 0;
    }

In the above example even though the method in invoked on Base class reference, method of the child will get invoked since its declared as virtual.

20. What do you mean by pure virtual functions in C++? Give an example?
Pure virtual function is a function which doesn't have an implementation and the same needs to be implemented by the the next immediate non-abstract class. (A class will become an abstract class if there is at-least a single pure virtual function and thus pure virtual functions are used to create interfaces in c++).

How to create a pure virtual function?
A function is made as pure virtual function by the using a specific signature, " = 0" appended to the function declaration as given below,

    class SymmetricShape {
        public:
            // draw() is a pure virtual function.
            virtual void draw() = 0;
    };

21. Why pure virtual functions are used if they don't have implementation / When does a pure virtual function become useful?
Pure virtual functions are used when it doesn't make sense to provide definition of a virtual function in the base class or a proper definition does not exists in the context of base class. Consider the above example, class SymmetricShape is used as base class for shapes with symmetric structure(Circle, square, equilateral triangle etc). In this case, there exists no proper definition for function draw() in the base class SymmetricShape instead the child classes of SymmetricShape (Cirlce, Square etc) can implement this method and draw proper shape.

22. What is virtual destructors? Why they are used?
[This c++ interview question is in a way related to polymorphism.]
Virtual destructors are used for the same purpose as virtual functions. When you remove an object of subclass, which is referenced by a parent class pointer, only destructor of base class will get executed. But if the destructor is defined using virtual keyword, both the destructors [ of parent and sub class ] will get invoked.

23. What you mean by early binding and late binding? How it is related to dynamic binding?
[This c++ interview question is related to question about virtual functions ]
Binding is the process of linking actual address of functions or identifiers to their reference. This happens mainly two times.

    During compilation : This is called early binding

For all the direct function references compiler will replace the reference with actual address of the method.

    At runtime : This is called late binding.

In case of virtual function calls using a Base reference, as in shown in the example of question no: 2, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at runtime.

Dynamic binding is another name for late binding.

24. What is meant by reference variable in C++?

In C++, reference variable allows you create an alias (second name) for an already existing variable. A reference variable can be used to access (read/write) the original data. That means, both the variable and reference variable are attached to same memory location. In effect, if you change the value of a variable using reference variable, both will get changed (because both are attached to same memory location).

How to create a reference variable in C++
Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.

    int a = 20;
    int& b = a;
               

The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a
Take a look at the below example to see how reference variables work.

    int main ()
    {
        int   a;
        int&  b = a;
    
        a = 10;
        cout << "Value of a : " << a << endl;
        cout << "Value of a reference (b) : " << b  << endl;
    
        b = 20;
        cout << "Value of a : " << a << endl;
        cout << "Value of a reference (b) : " << b  << endl;
    
        return 0;
    }

Above code creates following output.
Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20

25. What are the difference between reference variables and pointers in C++?
[This question is usually asked in a twisted way during c++ interviews. Sometimes the interviewer might use examples and ask you to find the error.]
Pointers    Reference Variables
Pointers can be assigned to NULL     References cannot be assigned NULL. It should always be associated with actual memory, not NULL.
Pointers can be (re)pointed to any object, at any time, any number of times during the execution.     Reference variables should be initialized with an object when they are created and they cannot be reinitialized to refer to another object
Pointer has own memory address and location on stack     Reference variables has location on stack, but shares the same memory location with the object it refer to.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


C++ Basic Interview Question and Answers
1.     What is C++?
      C++ is created by Bjarne Stroustrup of AT&T Bell Labs as an extension of C, C++ is an object-oriented computer language used in the development of enterprise and commercial applications. Microsoft’s Visual C++ became the premier language of choice among developers and programmers.
    

2.     What are the basic concepts of object oriented programming?
     

    It is necessary to understand some of the concepts used extensively in object oriented programming.These include
    Objects
    Classes
    Data abstraction and encapsulation
    Inheritance
    Polymorphism
    Dynamic Binding
    Message passing

3.     Define inheritance?
      The mechanism of deriving a new class (derived) from an old class (base class) is called inheritance. It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance is the process by which objects of one class acquire properties of objects of another class.
    

4.     Define polymorphism?
      Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviours in different instances.
   

5.     What are the features of C++ different from C?
     

    All the features of C are similiar to C++ except some features, such as polymorphism, operator overloading which are supported in C++ but not in C language.
    Both C and C++ language is similiar in their functionality but C++ provides with more tools and options.

     
C++ Interview Question and Answers
6.     What is encapsulation?
      The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Encapsulation containing and hiding information about an object, such as internal data structures and code.

7.     What is message passing?
      An object oriented program consists of a set of objects that communicate with each other. Message passing involves specifying the name of the object, the name of the function and the information to be sent.

8.     What are tokens in C++?
     

    The smallest individual units of a program is known as tokens. c++ has the following tokens :
    Keywords
    Identifiers
    Constants
    Strings
    Operators

9.     What is the use of enumerated data type?
      An enumerated data type is another user defined type which provides a way for attaching names to numbers thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2, and so on.
    

10.     What is the use of default constructor?
      A constructors that accepts no parameters is called the default constructor.If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A(). This constructor is an inline public member of its class. The compiler will implicitly define A::A() when the compiler uses this constructor to create an object of type A. The constructor will have no constructor initializer and a null body.

11.     Define Constructors?
      A constructor is a member function with the same name as its class. The constructor is invoked whenever an object of its associated class is created.It is called constructor because it constructs the values of data members of the class.

12.     How variable declaration in c++ differs that in c?
      C requires all the variables to be declared at the beginning of a scope but in c++ we can declare variables anywhere in the scope. This makes the programmer easier to understand because the variables are declared in the context of their use.

13.     Define destuctors?
     
 A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
    A destructors as the name implies is used to destroy the objects that have been created by a constructors.
    Like a constructor , the destructor is a member function whose name is the same as the class name but is precided by a tilde.

  14.     What is a class?
      A class is a collection of objects.
     

15.     what is the difference between c & c++?
     

    C++ ia an object oriented programing but C is a procedure oriented programing.
    C is super set of C++.
    C can’t suport inheritance, function overloading, method overloading etc. but c++ can do this.


16.     What are the few advantages of Inline function?
     

    It offers an improved macro facility.
    By using the inline functions, the user can split a large function with many nested modules of statement blocks into many small inline functions.

    17.     What is copy constructor?
      Copy constructor is a constructor function with the same name as the class and used to make deep copy of objects.
     

18.     What is default constructor?
      A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
    

19.     What is a scope resolution operator?
      The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.
   

20.     What is the difference between Object and Instance?
     

    An instance of a user-defined type is called an object. We can instantiate many objects from one class.
    An object is an instance of a class.

21.     What is the difference between macro and iniine?
      Inline follows strict parameter type checking, macros do not.
Macros are always expanded by preprocessor, whereas compiler may or may not replace the inline definitions.
     

22.     How variable declaration in c++ differs that in c?
      C requires all the variables to be declared at the beginning of a scope but in c++ we can declare variables anywhere in the scope. This makes the programmer easier to understand because the variables are declared in the context of their use.
   

23.     What is multiple inheritance?
      A class can inherit properties from more than one class which is known as multiple inheritance.
   

24.     what is the use of virtual destructor in c++?
     

    A destructor is automatically called when the object is destroyed.
    A virtual destructor in C++ is used primarily to prevent resource leaks by performing a clean-up of the object.



25.     What do you mean by reference variable in c++?
      A reference variable provides an alias to a previously defined variable.
Data -type & reference-name = variable name

26.     What is iterator class?
     

    Iterator class provides an access to the class which are inside the containers(it holds a group of objects in an organized way).
    The containers include the data structure, class and abstract data type.

27.     What are the types of declarations in C++?
     
There are so many types of declaration in C++ are :
    Variable declaration
    Constant declaration
    Function declaration
    Object declaration

28.     What are Smart pointers?
      Smart pointers are almost similar to pointers with additional features such as automatic destruction of a variable when it becomes out of scope and the throwing of exceptions that ensures the proper destruction of the dynamically allocated objects.
     

 29.     Explain function template?
      Function template provides a means to write generic functions for different data types such as integer, long, float or user defined objects.
     

    Discuss

30.     Explain class template?
      Class template provides a means to write a generic class for different types so that a class can have members based on generic types that do not need to be defined at the moment of creating the class or whose members use these generic types.
31.     What is difference between function overloading and operator overloading?
      A function is overloaded when same name is given to different function.
While overloading a function, the return type of the functions need to be the same.
     

    Discuss

32.     What are the advantages of inheritance?
     

    Code reusability
    Saves time in program development.

     

    Discuss

33.     What is a dynamic constructor?
     

    The constructor can also be used to allocate memory while creating objects.
    Allocation of memory to objects at the time of their construction is known as dynamic construction of objects.
    The memory is allocated with the help of the new operator.

     

    Discuss

34.     What is the difference between an Array and a List?
      The main difference between an array and a list is how they internally store the data. whereas Array is collection of homogeneous elements. List is collection of heterogeneous elements.
     

    Discuss

Your Name     Your Email-ID
   
Your Answer
35.     What is the use of ‘using’ declaration?
      A using declaration makes it possible to use a name from a namespace.
     
36.     What is the difference between a template class and class template?
      Template classA generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
Class templateA class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.
     

    Discuss

37.     What is friend function?
     

    The function declaration should be preceded by the keyword friend.
    The function definitions does not use either the keyword or the scope operator ::
    The functions that are declared with the keyword friend as friend function.
    Thus, a friend function is an ordinary function or a member of another class.

     

    Discuss

38.     What is a scope resolution operator?
      A scope resolution operator (::), can be used to define the member functions of a class outside the class.
     

    Discuss

39.     What do you mean by pure virtual functions?
      A pure virtual member function is a member function that the base class forces derived classes to provide. Any class containing any pure virtual function cannot be used to create object of its own type.
     

    Discuss

40.     What is a conversion constructor?
     

    A converting constructor is a single-parameter constructor that is declared without the function specifier explicit.
    The compiler uses converting constructors to convert objects from the type of the first parameter to the type of the converting constructor’s class.
41.     What is a container class? What are the types of container classes?
     

    A container class is a class that is used to hold objects in memory or external storage.
    A container class acts as a generic holder.
    A container class has a predefined behavior and a wellknown interface.
    A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory.
    When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

     

    Discuss

42.     What is Associative container?
     

    Associative containers are designed to support direct access to elements using keys. They are not sequential. There are four types of associatives containers :
    Set
    Multiset
    Map
    Multimap

     

    Discuss

43.     What is an iterator?
      Iterators are like pointers. They are used to access the elements of containers thus providing a link between algorithms and containers. Iterators are defined for specific containers and used as arguments to algorithms.
     

    Discuss

44.     What are the defining traits of an object-oriented language?
     

    The defining traits of an object-oriented langauge are :
    Encapsulation
    Inheritance
    Polymorphism

     

    Discuss

45.     What is this pointer?
      It is a pointer that points to the current object. This can be used to access the members of the current object with the help of the arrow operator.


In c program the main function could not return a value but in the c++ the main function shuld return a value.
////////////////////////////////////////////////////////////////////////
C++ Interview Questions

A list of top frequently asked C++ interview questions and answers are given below.
1) What is C++?

C++ is an object oriented programming language created by Bjarne Stroustrup. It is released in 1985.
2) What are the advantages of C++?

C++ doesn't only maintains all aspects from C language, it also simplify memory management and add several features like:

    Includes a new datatype known as a class.
    Allows object oriented programming.

3) What is the difference between C and C++?
No.    C    C++
1)    C follows the procedural style programming.    C++ is multi-paradigm. It supports both procedural and object oriented.
2)    Data is less secured in C.                      In C++, you can use modifiers for class members to make   i                                                                  inaccessible for outside users.
3)    C follows the top-down approach.                  C++ follows the bottom-up approach.
4)    C does not support function overloading.        C++ supports function overloading.
5)    In C, you can't use functions in structure.              In C++, you can use functions in structure.
6)    C does not support reference variables.                          C++ supports reference variables.
6)    In C, scanf() and printf() are mainly used for input/output.    C++ mainly uses stream cin and cout                                                                                            to perform input and output operations.
4) What is the difference between reference and pointer?
No.    Reference    Pointer

1)    References are less powerful than pointers. Once a reference is created, it can't refer to other object later.    Pointers provide the powerful facilities than references.
2)    References are safer and easier to use than pointers.     Pointers are comparatively difficult to use.
5) What is a class?

Class is a user-defined data type. Class defines the type definition of category of things. It defines a datatype, but it does not define the data it just specifies the structure of data.

You can create N number of objects from a class.
6) What is an object?

Object is the instance of a class. A class provides a blueprint for objects. So you can create an object from a class. The objects of a class are declared with the same sort of declaration that we declare variables of basic types.
7) What are the C++ access specifiers?

The access specifiers are used to define how to functions and variables can be accessed outside the class.

There are three types of access specifiers:

    Private: Functions and variables declared as private can be accessed only within the same class and they cannot be accessed outside the class they are declared.
    Public: Functions and variables declared under public can be accessed from anywhere.
    Protected: Functions and variables declared as protected cannot be accessed outside the class except a child class. This specifier is generally used in inheritance.

8) What is Object Oriented Programming (OOP)?

OOP is a methodology or paradigm that provides many concepts. The basic concepts of Object Oriented Programming are given below:

Classes and Objects: Classes are used to specify the structure of the data. They define datatype. You can create any number of objects from a class. Objects are the instances of classes.

Encapsulation: Encapsulation is a mechanism which binds the data and associated operations together and thus hide the data from outside world. Encapsulation is also known as data hiding. In C++, It is achieved using the access specifiers i.e. public, private and protected .

Abstraction: Abstraction is used to hide the internal implementations and show only the necessary details to the outer world. Data abstraction is implemented using interfaces and abstract classes in C++.

Some people confused about Encapsulation and abstraction. But they both are different.

Inheritance: Inheritance is used to inherit the property of one class into another class. It facilitates you to define one class in term of another class.
9) What is the difference between array and a list?

    Array is a collection of homogeneous elements while list is a collection of heterogeneous elements.
    Array memory allocation is static and continuous while List memory allocation is dynamic and random.
    In Array, users don't need to keep in track of next memory allocation while In list user has to keep in track of next location where memory is allocated.

10) What is the difference between new() and malloc()?

    new() is a preprocessor while malloc() is a function.
    There is no need to allocate the memory while using "new" but in malloc() you have to use sizeof().
    "new" initializes the new memory to 0 while malloc() gives random value in the newly allotted memory location.

11) What are the methods of exporting a function from a DLL?

There are two ways:

    By using the DLL's type library.
    Taking a reference to the function from the DLL instance.

12) Define friend function.

Friend function acts as friend of the class. It can access the private and protected members of the class. The friend function is not a member of the class but it must be listed in the class definition.
13) What is virtual function?

A virtual function is used to replace the implementation provided by the base class. The replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
14) When should we use multiple inheritance?

You can answer this question in three manners:
Never
Rarely
If you find that the problem domain cannot be accurately modeled any other way.
15) What is the destructor?

Destructor is used to delete any extra resources allocated by the object.
16) What is an overflow error?

It is a type of arithmetical error. It is happen when the result of an arithmetical operation been greater than the actual space provided by the system.
17) What is overloading?

C++ facilitates you to specify more than one definition for a function name or an operator in the same scope. It is called function overloading and operator overloading respectively.
18) What is function overriding?

If you inherit a class into a derived class and provide a definition for one of the base class's function again inside the derived class, then this function is called overridden function and this mechanism is known as function overriding.
19) What is virtual inheritance?

Virtual inheritance facilitates you to create only one copy of each object even if the object appears more than one in the hierarchy.
20) What is constructor?

Constructor is a special method that initializes object. It name must be same as class name.
21) What is the purpose of "delete" operator?

The "delete" operator is used to release the dynamic memory created by "new" operator.
22) Explain this pointer?

This pointer holds the address of current object.
23) What does Scope Resolution operator?

A scope resolution operator(::) is used to define the member function outside the class.
24) What is the difference between delete and delete[]?

Delete [] is used to release the array of allocated memory which was allocated using new[] whereas delete is used to release one chunk of memory which was allocated using new.
25) Define the private, protected and public in C++?

Private: The data members and functions cannot be accessed from outside the class.

Protected: The data members and functions are accessible to derived class only.

Public: The data members and functions can be accessed from outside the class.

   

9 comments:

  1. These questions are pretty thorough. My only problem is that they seem a bit too textbook. I think most companies will focus on coding C++ interview questions: https://www.testdome.com/d/cpp-interview-questions/7
    These questions require solving a programming problem, fixing bugs, or implementing a solution. Companies tend to favor these work-sample tasks over theoretical knowledge.

    ReplyDelete
  2. Salve


    Thanks for highlighting this and indicating about #topic where more study and thought is necessary.

    in 16 bit DOS programming, keep() is used to resident a program in memory, but in 32 bit / 64 bit C compiler, how can I use this?If keep() does not work, then what is the alternative function that works?


    Great effort, I wish I saw it earlier. Would have saved my day :)


    Thank you

    ReplyDelete
  3. Hi Bhargava,


    Great piece on C++ Interview Questions and Answers , I’m a fan of the ‘flowery’ style Looking forward to more long form articles ??

    Totally new to Linux. I am running an older Acer Aspire one laptop with a 1.6 ghtz processor and plenty of ram. I downloaded Linux Mint (Cinnamon version) along with the proper unetbootin-windows-613 to my 8gb blank USB...well, I believe it is the proper version. I did get the 32 bit as that is what my system is.
    But nice Article Mate! Great Information! Keep up the good work!


    Merci,
    Abhiram

    ReplyDelete
  4. wow this post is amazing .. thanks for sharing please see my post also here is my post for
    Top 10 best books to learn C Programming

    ReplyDelete
  5. Apa yang Anda miliki, pada dasarnya, adalah bagian dari keuntungan perusahaan - dan, harus dikatakan, kerugiannya. Tujuannya, tentu saja, adalah agar nilai perusahaan - dan sebagai hasilnya, nilai sahamnya - naik saat Anda menjadi pemegang saham. cek juga markets.co.id dan Perbedaan Pasar Modal Syariah dan Pasar Modal Konvensional

    ReplyDelete
  6. Excellent data with lots of information. I have bookmarked this page for my future reference. Do share more updates.
    Full Stack Developer Course in Chennai
    Full Stack Developer Online Course
    Full Stack Online Course

    ReplyDelete
  7. I just wanted to say that I really enjoyed reading your blog post. The topic was really interesting and I learned a lot from it. The insights you shared were really helpful and I'm looking forward to reading more from you in the future!
    Full stack training in Pune

    ReplyDelete

commnet here