C++ Interview Questions

If you are appearing for a technical round of interview for C++, here’s a list of the top 71 interview questions with answers to help you prepare.

Last updated: Aug 29, 2021



Q. 1: What do you mean by a Move Constructor?

One of the latest features of C++11 are a Move Constructor and a Move Assignment operator. We know that a Copy Constructor and a Copy Assignment is used to make a copy of one object to another, the Move Constructor and Move Assignment is to shift the ownership of the resources from one object to other. This is less expensive that object to object copy. A Move Constructor and Move Assignment operator is not provided by the compiler by default and one needs to implement the same.



Q. 2: What is the difference between a Copy Constructor and an Assignment Operator?

Though both of them perform similar tasks, the differences between a Copy Constructor and an assignment operator is as follows:

While the former is an overloaded Constructor the latter is a Bitwise Operator.

The Copy Constructor can be used to initialize a new object with an existing object which is an overloaded Constructor while an assignment operator is invoked only when an object is being assigned to another object.

An assignment operator returns a value by default unlike a Copy Constructor. Both of them perform shallow copying by default. An overloaded assignment operator can be used to do deep copying.



Q. 3: What do you mean by Stack unwinding?

Stack Unwinding happens during exception handling. During an exception occurrence, the destructor is called to destroy all local objects for the place where the exception was thrown and where it was caught. An exception causes the control to pass on from a try block to the respective exception handler. The destructors for all constructed automatic objects are called at run time which where created since the beginning of the try block. The automatic objects are destroyed in reverse order of their construction.

The terminate() function is invoked during Stack Unwinding on a destructor for a unhandled exception.

The following example demonstrates this:

#include <iostream>
using namespace std;

struct E {
    const char* message;
    E(const char* arg) : message(arg) { }
};

void my_terminate() {
    cout << "Call to my_terminate" << endl;
};

struct A {
    A() { cout << "In constructor of A" << endl; }
    ~A() {
        cout << "In destructor of A" << endl;
        throw E("Exception thrown in ~A()");
    }
};

struct B {
    B() { cout << "In constructor of B" << endl; }
    ~B() { cout << "In destructor of B" << endl; }
};

int main() {
    set_terminate(my_terminate);
    try {
        cout << "In try block" << endl;
        A a;
        B b;
        throw("Exception thrown in try block of main()");
    }
    catch (const char* e) {
        cout << "Exception: " << e << endl;
    }
    catch (...) {
        cout << "Some exception caught in main()" << endl;
    }
        cout << "Resume execution of main()" << endl;
}

The output of this example:

Output:

In try block
In constructor of A
In constructor of B
In destructor of B
In destructor of A
Call to my_terminate

In the try block, two automatic objects are created: a and b. The try block throws an exception of type const char*. The handler catch (const char* e) catches this exception. The C++ run time unwinds the stack, calling the destructors for a and b in reverse order of their construction. The destructor for a throws an exception. Since there is no handler in the program that can handle this exception, the C++ run time calls terminate(). (The function terminate() calls the function specified as the argument to set_terminate(). In this example, terminate() has been specified to call my_terminate().)



Q. 4: Differentiate between a deep copy and a shallow copy?

Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.

Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.

Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.

If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.



Q. 5: What is Name Mangling in C++? Write an example for the same?

Name mangling is the process through which the C++ compilers give each function a in program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique. In C++, generally programs have at-least a few functions with the same name.

Example:

In general, member names are made unique by concatenating the name of the member with that of the class given the declaration:

class Bar
{
    public:
        int ival;
        ...
};

ival becomes something like:

// a possible member name mangling
ival__3Bar

Consider this derivation:

class Foo : public Bar
{
    public:
        int ival;
        ...
}

The internal representation of a Foo object is the concatenation of its base and derived class members.

// Pseudo C++ code
// Internal representation of Foo
class Foo
{
    public:
        int ival__3Bar;
        int ival__3Foo;
        ...
};

Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).



Q. 6: What are the main characteristics of Static Functions?

The main characteristics of static functions are as follows:



Q. 7: Will the inline function be compiled as the inline function always? Justify your answer.

An inline function is a request and not a command. Hence it won't be compiled as an inline function always.

Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for in-lining are compiler dependent.



Q. 8: How can a '::' operator be used as unary operator?

The scope resolution operator '::' can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.



Q. 9: How do I write my own zero-argument manipulator that should work same as hex?

#include <iostream>

ostream& myhex ( ostream &o )
{
    o.setf ( ios::hex) ;
    return o ;
}

int main( )
{
    cout << endl << myhex << 2000 ;
    return 0;
}

Output:

2000


Q. 10: How do you refer to a name of class or function that is defined within a namespace?

There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator '::' through the using keyword. This is shown in following example:

There are two ways in which we can refer to a name of class or function that is defined within a namespace: Using scope resolution operator through the using keyword. This is shown in following example:

namespace name1
{
    class sample1
    {
        // code
    } ;
}

namespace name2
{
    class sample2
    {
        // code
    } ;
}

using namespace name2;
void main( )
{
    name1::sample1 s1 ;
    sample2 s2 ;
}

Here, class sample1 is referred using the scope resolution operator.

On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.

Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly refer to class sample2 because of the statement using namespace name2 ; the using keyword declares all the names in the namespace to be in the current scope. So we can use the names without any qualifiers.



Q. 11: While overloading a binary operator can we provide default values? Justify your answer.

No!. This is because even if we provide the default arguments to the parameters of the overloaded operator function we would end up using the binary operator incorrectly. This is explained in the following example:

sample operator + ( sample a, sample b = sample (2, 3.5f ) )
{
}

void main( )
{
    sample s1, s2, s3 ;
    s3 = s1 + ; // error
}


Q. 12: Write a program that allows to create only one instance of a class?

This concept is used to create a Singleton Class. Below is code snippet demonstrating the same:

#include

class sample
{
    static sample *ptr;
    private:
        sample( )
        {
        }
    public:
        static sample* create( )
        {
            if ( ptr == NULL )
            ptr = new sample;
            return ptr;
        }
};

sample *sample::ptr = NULL ;
void main( )
{
    sample *a = sample::create( );
    sample *b = sample::create( );
}

Here, the class sample contains a static data member ptr, which is a pointer to the object of same class. The constructor is private which avoids us from creating objects outside the class.

A static member function called create( ) is used to create an object of the class. In this function the condition is checked whether or not ptr is NULL, if it is then an object is created dynamically and its address collected in ptr is returned. If ptr is not NULL, then the same address is returned. Thus, in main( ) on execution of the first statement one object of sample gets created whereas on execution of second statement, b holds the address of the first object. Thus, whatever number of times you call create( ) function, only one object of sample class will be available.



Q. 13: Write a program that implements a date class containing day, month and year as data members. Implement assignment operator and copy constructor in this class.

#include<iostream>

class date
{
    private :
        int day;
        int month;
        int year;
    public :
        date ( int d = 0, int m = 0, int y = 0 )
        {
            day = d;
            month = m;
            year = y;
        }

        // copy constructor
        date ( date &d )
        {
            day = d.day;
            month = d.month;
            year = d.year;  
        }

        // an overloaded assignment operator
        date operator = ( date d )
        {
            day = d.day;
            month = d.month;
            year = d.year;
            return d;  
        }

        void display( )
        {
            cout << day << "/" << month << "/" << year;
        }
};

void main( )
{
    date d1 ( 25, 9, 1979 );
    date d2 = d1;
    date d3;
    d3 = d2;
    d3.display( );
}


Q. 14: When the constructor of a base class calls a virtual function, why doesn't the override function of the derived class gets called?

While building an object of a derived class first the constructor of the base class and then the constructor of the derived class gets called. The object is said an immature object at the stage when the constructor of base class is called. This object will be called a matured object after the execution of the constructor of the derived class. Thus, if we call a virtual function when an object is still immature, obviously, the virtual function of the base class would get called. This is illustrated in the following example.

#include <iostream>

class base
{
    protected:
        int i;
    public:
        base ( int ii = 0 )
        {
            i = ii;
            show( );
        }

        virtual void show( )
        {
            cout << "base's show( )" << endl;
        }
};

class derived : public base
{
    private:
        int j;
    public :
        derived ( int ii, int jj = 0 ) : base ( ii )
        {
            j = jj;
            show( );
        }
        void show( )
        {
            cout << "derived's show( )" << endl;
        }
};

void main( )
{
    derived dobj ( 20, 5 );
}

Output:

base's show( )
derived's show( )


Q. 15: Write a program that will convert an integer pointer to an integer and vice-versa.

The following program demonstrates this.

#include<iostream>

void main( )
{
    int i = 65000;

    int *iptr = reinterpret_cast ( i );
    cout << endl << iptr;

    iptr++;
    cout << endl << iptr;

    i = reinterpret_cast ( iptr );
    cout << endl << i;

    i++;
    cout << endl << i;
}


Q. 16: What is Singleton Design pattern? Explain with an example how to use Singleton Design pattern to design a class that is Thread safe

Design Patterns are reusable solutions that can be applied to recurring Object Oriented Design problems. Singleton is one such design pattern that comes under the category of Creational Design Pattern. It can be used to design such a class which can at most have only single instance at any point of time and cant be instantiated further. This concept can applied for creation of a logger or hardware interface class which can have only one instance running at all times.

Example of Singleton class that is thread safe:

In order to make the class thread safe, one needs to only create an instance when no other instance exists as below:

class Singleton
{
    public:
        static Singleton* getinstance();
        ...
    private:
        static Singleton* volatile newinstance;
};

Singleton* Singleton::getinstance()
{
    if (newinstance == NULL)
    {
        Guarder<Lock>lock(m_lock);
        if (newinstance == NULL)
        {
            Singleton* volatile temp = static_cast< Singleton* >(operator  new (sizeof(Singleton)));
            Newinstance = temp;
        }
    }
    return newinstance;
}


Q. 17: What is a Smart Pointer? Where it is used? What are types of Smart Pointers? Implement a generic Smart Pointer which can be used for all datatypes.

Smart Pointers are used for better garbage collection so that there are no memory leaks. Using Smart Pointers, there is no need to call delete for any memory allocated dynamically and it gets automatically deallocated.

Smart Pointers Implementations can be found in C++11 and higher versions. C++11 libraries provide four kinds of Smart pointers namely: auto_ptr, unique_ptr, shared_ptr and weak_ptr.

The below example implements a generic smart pointer which can used for all datatypes:

#include<iostream>
using namespace std;

template <class T>
class SmartPtr
{
    T *ptr; 
    public:
        // Constructor
        explicit SmartPtr(T *p = NULL) { ptr = p; }
        // Destructor
        ~SmartPtr() { delete(ptr); }
        // Overloading dereferncing operator
        T & operator * () {  return *ptr; }
        // Overloding arrow operator so that members of T can be accessed
        // like a pointer (useful if T represents a class or struct or 
        // union type)
        T * operator -> () { return ptr; }
};

int main()
{
    SmartPtr<int> ptr(new int());
    *ptr = 20;
    cout << *ptr;
    return 0;
}


Q. 18: What are the differences between Vector and List in STL?

Vectors and Lists are defined under C++ Standard Template Library (STL). These data structures are basically sequential containers implemented using STLs.

The differences between them are as follows:



Q. 19: What are virtual classes? What is the order of invocation of constructors for them?

You can make a class virtual if it is a base class that has been passed to more than one derived class, as might happen with multiple inheritance.

A base class can't be specified more than once in a derived class:

class B { ...};
class D : B, B { ... };  // ILLEGAL

However, a base class can be indirectly passed to the derived class more than once:

class X : public B { ... }
class Y : public B { ... }
class Z : public X, public Y { ... }  // OK

In this case, each object of class Z will have two sub-objects of class B.

If this causes problems, you can add the keyword "virtual" to a base class specifier. For example,

class X : virtual public B { ... }
class Y : virtual public B { ... }
class Z : public X, public Y { ... }

B is now a virtual base class, and class Z has only one sub-object of class B.

Constructors for Virtual Base Classes:

Constructors for virtual base classes are invoked before any non-virtual base classes. If the hierarchy contains multiple virtual base classes, the virtual base class constructors are invoked in the order in which they were declared. Any non-virtual bases are then constructed before the derived class constructor is called. If a virtual class is derived from a non-virtual base, that non-virtual base will be first, so that the virtual base class can be properly constructed. For example, this code

class X : public Y, virtual public Z
    X one;
produces this order:
    Z();   // virtual base class initialization
    Y();   // non-virtual base class
    X();   // derived class


Q. 20: What is an abstract class and where do we define the same?

An abstract class is a class which has atleast one pure virtual function. An abstract class cant be instantiated be can be overridden in a derived class as below:

Example:

class Base {
    public:
        virtual void Get() = 0;
        virtual bool Get(int i) = 0;
        virtual int Get(float x) = 0;
        virtual ~Base() { }
};

class Derived1 : public Base {
    bool value;
    public:
        void Get() { }
        bool Get(int i) { return i;}
        int Get(float x) { return (int)x;}
};

class Derived2 : public Base {
    int value;
    public:
        void Get() { }
        bool Get(int i) { return i;}
        int Get(float x) { return (int)x;}
};

int main()
{
    int k=5;
    int temp = base->Get(k);  
    cout<<"temp is"<<base->Get(k)<<endl;
    return 0;
}


Q. 21: Write a program to dynamic allocate a 2D Array, assign values to the same, print the values and deallocate the 2D Array.

#include <iostream>
// M x N matrix
#define M 4
#define N 5

// Dynamically Allocate Memory for 2D Array in C++
int main()
{
    // dynamically allocate memory of size M*N
    int* A = new int[M * N];

    // assign values to allocated memory
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            *(A + i*N + j) = rand() % 100;

    // print the 2D array
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
            std::cout << *(A + i*N + j) << " ";    // or (A + i*N)[j]);
        std::cout << std::endl;
    }

    // deallocate memory
    delete[] A;
    return 0;
}


Q. 22: Write a program in C++ to found out whether a word is palindrome or not?

#include <string>
#include <stdexcept>
#include <iostream>

using namespace std;

class Palindrome
{
    public:
        static bool isPalindrome(const std::string& word)
        {
            static int i,j;
            static int count;
            while(word[count]!='\0')
                count++;
            cout<<"count is"<<count<<endl;
            i=0;
            j=count-1;
            while(i<j)
            {
                cout<<endl<<"word[i]"<<word[i]<<endl<<"word[j]"<<word[j]<<endl;
                if(tolower(word[i++])!=tolower(word[j--]))
                {
                    cout<<endl<<word<<" is not a Palindrome"<<endl;
                    return 0;
                }
            }
            cout<<endl<<word<<" is a palindrome"<<endl;
            count = i = i= 0;
            return 1;
        }
};

#ifndef RunTests
int main()
{
    std::cout << Palindrome::isPalindrome("Deleveled");
    std::cout << Palindrome::isPalindrome("Malayalam");
    std::cout << Palindrome::isPalindrome("Bab");
    std::cout << Palindrome::isPalindrome("Balam");
}
#endif


Q. 23: What is upcasting and downcasting? What is object slicing in case of upcasting?

Upcasting is converting a derived class reference or pointer to a base class. In other words, upcasting allows us to treat a derived type as though it were its base type. It is always allowed for public inheritance, without an explicit type cast. This is a result of the is-a relationship between the base and derived classes. Upcasting allows us to treat a derived type as though it were its base type.

When a derived class object is passed by value as a base class object, the specific behaviors of a derived class object are sliced off. We're left with a base class object. In other words, if we upcast (Upcasting and Down Casting) to an object instead of a pointer or reference, the object is sliced. As a result, all that remains is the sub object that corresponds to the destination type of our cast and which is only a part of the actual derived class.

Converting a base-class pointer (reference) to a derived-class pointer (reference) is called downcasting. Downcasting is not allowed without an explicit typecast. The reason for this restriction is that the is-a relationship is not, in most of the cases, symmetric. A derived class could add new data members, and the class member functions that used these data members wouldn't apply to the base class.

// Example of upcasting and downcasting:

class Parent {
    public:
        void sleep() {}
};

class Child: public Parent {
    public:
        void gotoSchool(){}
};

int main( )
{
    Parent parent;
    Child child;

    // upcast - implicit type cast allowed
    Parent *pParent = &child;

    // downcast - explicit type case required
    Child *pChild =  (Child *) &parent;
    pParent -> sleep();
    pChild -> gotoSchool();
    return 0;
}


Q. 24: What is RTTI and how it can be implemented?

In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program runtime execution

For example, dynamic_cast uses RTTI and following program fails with error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.

// CPP program to illustrate  
// Run Time Type Identification  

#include<iostream>

using namespace std;

class B { };
class D: public B {};

int main()
{
    B *b = new D;
    D *d = dynamic_cast<D*>(b);
    if(d != NULL)
        cout<<"works";
    else
        cout<<"cannot cast B* to D*";
    getchar();
    return 0;
}
// This is give a run time error: "cannot dynamic_cast 'b' (of type 'class B*') to type 'class D*' (source type is not polymorphic)"
// Adding a virtual function to the base class B makes it working.
// CPP program to illustrate  
// Run Time Type Identification  

#include<iostream>

using namespace std;

class B { virtual void fun() {} };
class D: public B { };

int main()
{
    B *b = new D;
    D *d = dynamic_cast<D*>(b);
    if(d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}


Q. 25: How do you create a thread? Describe how to pass multiple arguments to the thread?

Using pthread_create we create a thread. We can use the reference of a structure to pass multiple arguments to the 4th parameter as below:

#include <iostream.h>
#include <pthread.h>

struct arg_struct {
    int arg1;
    int arg2;
};

void *print_the_arguments(void *arguments)
{
    struct arg_struct *args = (struct arg_struct *)arguments;
    cout<< args -> arg1<<endl;
    cout<< args -> arg2<<endl;
    pthread_exit(NULL);
    return NULL;
}

int main()
{
    pthread_t some_thread;
    struct arg_struct args;
    args.arg1 = 5;
    args.arg2 = 7;
    if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
        printf("Uh-oh!
");
        return -1;
    }
    return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}


Q. 26: Can constructor be virtual and what about destructor? If yes why and if not why?

We cant make a class constructor virtual in C++ to create polymorphic objects. C++ being static typed (the purpose of RTTI is different) language, it is meaningless to the C++ compiler to create an object polymorphically. The compiler must be aware of the class type to create the object. In other words, what type of object to be created is a compile time decision from C++ compiler perspective. If we make constructor virtual, compiler flags an error. In fact except inline, no other keyword is allowed in the declaration of constructor.

Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior.

// CPP program without virtual destructor 
// causing undefined behavior

#include<iostream>

using namespace std;

class base {
    public:
        base()     
        { cout<<"Constructing base 
"; }
        ~base()
        { cout<<"Destructing base 
"; }     
};

class derived: public base {
    public:
        derived()     
        { cout<<"Constructing derived 
"; }
        ~derived()
        { cout<<"Destructing derived 
"; }
};

int main(void)
{
    derived *d = new derived();  
    base *b = d;
    delete b;
    getchar();
    return 0;
}


Q. 27: What is a Sparse Matrix? How do you implement sparse array using STL map?

A Sparse Matrix is an array of elements in which many elements have a value of zero.

#include <string.h>
#include <iostream>
#include <map>
#include <utility>

using namespace std;

int main()
{
    map<int, string> Employees;

    // 1) Assignment using array index notation
    Employees[5234] = "Mike C.";
    Employees[3374] = "Charlie M.";
    Employees[1923] = "David D.";
    Employees[7582] = "John A.";
    Employees[5328] = "Peter Q.";

    cout << "Employees[3374]=" << Employees[3374] << endl << endl;
    cout << "Map size: " << Employees.size() << endl;
    cout << endl << "Natural Order:" << endl;

    for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)
    {
        cout << (*ii).first << ": " << (*ii).second << endl;
    }

    cout << endl << "Reverse Order:" << endl;

    for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend(); ++ii)
    {
        cout << (*ii).first << ": " << (*ii).second << endl;
    }
}

Output:

Employees[3374]=Charlie M.
Map size: 5
Natural Order:
1923: David D.
3374: Charlie M.
5234: Mike C.
5328: Peter Q.
7582: John A.
Reverse Order:
7582: John A.
5328: Peter Q.
5234: Mike C.
3374: Charlie M.
1923: David D.


Q. 28: How do you implement a Queue in C++ using one or more stacks?

In the en-queue operation, the new element is entered at the top of Stack1. In de-queue operation, if Stack2 is empty then all the elements are moved to Stack2 and top of Stack2 is returned.

enQueue(q, k):

Push the element 'k' to Stack1

deQueue(q):

While Stack1 is not empty and Stack2 is empty, pop the elements from Stack1 and push to Stack2.

The top of the Stack2 popped out is returned.

Program to perform the above:

#include <iostream>

using namespace std;

// implementing the stack class
class Stack
{
    int top;
    public:
    int a[10];  //Maximum size of Stack

    Stack()
    {
        top = -1;
    }

    // declaring all the function
    void push(int x);
    int pop();
    bool isEmpty();
};

// function to insert data into stack
void Stack::push(int x)
{
    if(top >= 10)
    {
        cout << "Stack Overflow";
    }
    else
    {
        a[++top] = x;
        cout << endl<<  "Element Inserted into Stack"<< x;
    }
}

// function to remove data from the top of the stack
int Stack::pop()
{
    if(top < 0)
    {
        cout << "Stack Underflow 
";
        return 0;
    }
    else
    {
        return (a[top--]);
    }
}

// function to check if stack is empty
bool Stack::isEmpty()
{
    if(top < 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

// implementing the queue class
class Queue {
    public:
        Stack S1, S2;
        //declaring enqueue method
        void enqueue(int x);
        //declaring dequeue method
        int dequeue();
};

// enqueue function
void Queue :: enqueue(int x)
{
    S1.push(x);
    cout << "Element Inserted into Queue "<< x << endl;
}

// dequeue function
int Queue :: dequeue()
{
    int x, y;

    while(!S1.isEmpty())
    {
        // take an element out of first stack
        x = S1.pop();
        // insert it into the second stack
        S2.push(x);
    }

    // removing the element
    y = S2.pop();

    // moving back the elements to the first stack
    while(!S2.isEmpty())
    {
        x = S2.pop();
        S1.push(x);
    }

    return y;
}

// main function
int main()
{
    Queue q;
    q.enqueue(10);
    q.enqueue(100);
    q.enqueue(1000);
    cout << endl<< "Removing element from queue" << q.dequeue();
    return 0;
}


Q. 29: Write a Message class in C++ containing apis to get and put messages? Ensure that objects of the Message class are destroyed properly in reverse order of creation.

The above can be demonstrated using the below program:

class Message
{
    public:
        void put_message(void);
        void get_message(void);
        int message;
        Message(void)
        {
            message=0;
            cout<<"Objects Created"<<endl;
        }
        Message(int k)
        {
            message=k;
        }
        ~Message() {
            cout<<"Objects Destroyed"<<endl;
        }
}q;

void Message::put_message(void)
{
    message=12345;
}

void Message::get_message(void)
{
    cout<<"The message is "<<message<<endl;
}

int main()
{
    Message k(67890);
    q.put_message();
    q.get_message();
    k.get_message();
    return 0;
}

Output:

Objects Created
The message is 12345
The message is 67890
Objects Destroyed
Objects Destroyed


Q. 30: What is the difference between a reference and a pointer?

Pointers and References are two different concepts. A pointer in C++ is basically a variable that stores the memory address of another variable. While references act as an alias name for an existing variable that needs to be initialized at the time of declaration. This is not the case with pointers.



Q. 31: What is the difference between the local and global scope of a variable and what is their order of precedence if they both are of the same name?

The local scope of a variable allows the variable to work inside a restricted block of code. For instance, if it is declared inside a function, you cannot access it from the main function without calling the function whereas the global scope of a variable allows the variable to be accessible throughout the entire program.

It is a well-established fact that whenever a program has a local and global variable, precedence is given to the local variable within that program.



Q. 32: What is the difference between a++ and ++a?



Q. 33: Write a C++ function to count the number of lowercase alphabets in a text file.

int count_lowercase()
{
    ifstream fin("file_name.txt");
    char ch;
    int count = 0;

    while(!fin.eof())
    {
        fin>>ch;
        if(islower(ch))
            count++;
    }
    fin.close();

    return count;
}


Q. 34: How would you find the sum of two numbers without using the '+' operator in C++?

#include<iostream> 

using namespace std;

void sum(int n1, int n2)
{
    int sum = -( -n1-n2 ); 
    cout << sum << endl; 
}

int main() 
{
    sum(5,5);
    sum(6,4); 
    return 0;
}


Q. 35: What is the difference between typecasting and automatic type conversion? Explain with the help of an example.

Typecasting in C++ is done by the programmer in order to convert a value from one data type to another data type.

Example:

float pi = (float) 22/7;

On the other hand, automatic type conversion is automatically done by the C++ compiler as and when required.

Example:

float value = 10;


Q. 36: Why do we use templates in C++?

Templates in C++ are a quick and efficient way of achieving polymorphism, an important concept in OOP. It helps us in handling various types of parameters and hence reduces efforts in debugging and testing the code.



Q. 37: What is meant by event-driven programming? In what way is it supported in C++?

Event-driven programming refers to a programming paradigm in which the flow of control is given by events such as user-actions or threads. C++ supports event-driven programming as it consists of the main function that lists the events to be executed sequentially and triggers a callback function as soon as an event is identified, such as looping or a function call.



Q. 38: What are the demerits of using inline functions?

One of the major disadvantages of inline functions in C++ is the immense wastage of computer memory by repetitive occurrences of the same function code. Inline functions involve several function calls. Therefore, for each function call, the entire code is processed, again and again, increasing the time-complexity of our program.

Moreover, there are certain situations where inline functions do not work. They are:



Q. 39: How would you access the private members of a class without using any member function of that class?

C++ gives the programmer the provision to access private as well as protected data members of a class outside the class or to other classes with the help of the friend function or friend class.



Q. 40: What is 'this' pointer?

'this' pointer is used to hold the address of the current object. In simple words, 'this pointer' points to the current object of the class.



Q. 41: Write a program in C++ to find and print the sum of all the values ending with 7 in a 2D array.

#include <iostream>

using namespace std;

int main()
{
    int sum = 0, i , j, m, n, remainder;
    int A[10][10];

    cout<<"Enter the number of rows of the 2D array: "<<endl;
    cin>>m;
    cout<<"Enter the number of columns of the 2D array: "<<endl;
    cin>>n;

    // Input of the array
    cout<<"Enter the elements of the array: "<<endl;
    for (i =0; i < m; i++)
    {
        for(j = 0; j < n; j++)
        {
            cin>>A[i][j];
        }
    }

    // Logic to find sum of elements ending with 7.
    for (i =0; i < m; i++)
    {
        for(j = 0; j < n; j++)
        {
            remainder = A[i][j]%10;
            if(remainder == 7)
                sum = sum + A[i][j];
        }
    }

    cout<<"The sum of elements with unit's digit 7 is: "<< sum<<endl;
    
    return 0;
}


Q. 42: How would you create a self-referential structure? Is it possible to create a self-referential class as well?

Self-referential structures are basically structures that have one or more than one pointers pointing to the same type of structure as their members. In simple words, structures that point to the same type of structures are called self-referential structures. Yes, it is possible to create a self-referential class as well in order to implement a linked list or a tree.



Q. 43: What is the difference between delete and delete[]?

While creating and allocating memory to a variable with the help of the "new" keyword, we can deallocate the memory associated with it by the help of the "delete[]" operator whereas, while creating and allocating memory to a non-array object with new, we can deallocate the memory with the help of the "delete" operator.



Q. 44: What are the reasons for memory leaks?

The major reasons for memory leaks are as follows:



Q. 45: Write a function in C++ to modify the content of the array in such a way that the elements that are multiples of 5 are swapped with its adjacent element.

void Swap(int array[], int size)
{
    int i, temp;

    for(i = 0; i < size-2; i++)
        if(array[i]%5 == 0)
        {
            temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;
            i++;
        }

    cout<<"The swapped array is: "<<endl;
    for(i = 0; i <= size-1; i++)
    {
        cout<<array[i]<<"	";
    }
}


Q. 46: Write a function in C++ to modify the content of an array in such a way that elements present every even location of the array is swapped with those present in odd locations

void Position_Swap(int array[], int size)
{
    int limit, swap;
    
    if(size%2 != 0)
        limit = size - 1;
    else
        limit = size;

    for(int i =0; i < limit - 1; i+=2)
    {
        swap = array[i];
        array[i] = array[i+1];
        array[i+1] = swap;
    }
}


Q. 47: How would you find the product of alternate elements of a 2D array?

void Alter_sum(int A[], int m, int n)
{
    int product =0, temp = 1;

    for(int i = 0; i < m; i++)
        for(int j =0; j < n; j++)
        {
            if(temp % 2 != 0)
            product = product*A[i][j];
            temp++;
        }

    cout<<"The3 product of the alternate elements of the array is: ", product);
}


Q. 48: How would you check if two numbers are equal or not without the use of any relational operator in C++?

#include <iostream>

using namespace std; 

void check(int n1, int n2) 
{
    if ( !(n1 ^ n2) ) // Performing XNOR operation
        cout<< n1 << " is equal to " << n2 <<endl; 
    else 
        cout<< n1 << " is not equal to " << n2 <<endl; 
}

int main() 
{
    check(2,2);
    check(2,4);

    return 0;
}


Q. 49: What are virtual functions – Write an example?

Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.

Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)

For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived class, because bp points to an object of Derived class.

#include<iostream>

using namespace std;

class Base {
    public:
        virtual void show() { cout<<" In Base 
"; }
};

class Derived: public Base {
    public:
        void show() { cout<<"In Derived 
"; }
};

int main(void) {
    Base *bp = new Derived;        
    bp->show(); // RUN-TIME POLYMORPHISM
    return 0;
}


Q. 50: What are VTABLE and VPTR?

vtable is a table of function pointers. It is maintained per class.

vptr is a pointer to vtable. It is maintained per object (See this for an example).

Compiler adds additional code at two places to maintain and use vtable and vptr.



Q. 51: 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:



Q. 52: 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:



Q. 53: What is the difference between an array and a list?



Q. 54: What is the difference between new() and malloc()?



Q. 55: What is a 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.

A virtual function is a member function which is present in the base class and redefined by the derived class.

When we use the same function name in both base and derived class, the function in base class is declared with a keyword virtual.

When the function is made virtual, then C++ determines at run-time which function is to be called based on the type of the object pointed by the base class pointer. Thus, by making the base class pointer to point different objects, we can execute different versions of the virtual functions.



Q. 56: What is a destructor?

A Destructor is used to delete any extra resources allocated by the object. A destructor function is called automatically once the object goes out of the scope.

Rules of destructor:



Q. 57: What is an overflow error?

It is a type of arithmetical error. It happens when the result of an arithmetical operation been greater than the actual space provided by the system.



Q. 58: What is overloading?

When a single object behaves in many ways is known as overloading. A single object has the same name, but it provides different versions of the same function.

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.1. Operator overloading: Operator overloading is a compile-time polymorphism in which a standard operator is overloaded to provide a user-defined definition to it. For example, '+' operator is overloaded to perform the addition operation on data types such as int, float, etc.

Operator overloading can be implemented in the following functions:



Q. 59: 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.



Q. 60: What is a constructor?

A Constructor is a special method that initializes an object. Its name must be same as class name.



Q. 61: What is a pure virtual function?

The pure virtual function is a virtual function which does not contain any definition. The normal function is preceded with a keyword virtual. The pure virtual function ends with 0.



Q. 62: What is a class template?

A class template is used to create a family of classes and functions. For example, we can create a template of an array class which will enable us to create an array of various types such as int, float, char, etc. Similarly, we can create a template for a function, suppose we have a function add(), then we can create multiple versions of add().



Q. 63: What is a virtual destructor?

A virtual destructor in C++ is used in the base class so that the derived class object can also be destroyed. A virtual destructor is declared by using the ~ tilde operator and then virtual keyword before the constructor.



Q. 64: What is a storage class? Mention the storage classes names in C++.

Storage class specifies the life or scope of symbols such as variable or functions. The following are storage classes supported in C++



Q. 65: What is the role of mutable storage class specifier?

A constant class object’s member variable can be altered by declaring it using mutable storage class specifier. Applicable only for non-static and non-constant member variable of the class.



Q. 66: Distinguish between shallow copy and deep copy.

Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field by field from object to another. Deep copy is achieved using copy constructor and or overloading assignment operator.



Q. 67: How can we catch all kind of exceptions in a single catch block?

The catch block with ellipses as follows

catch(…)
{
    // code
}


Q. 68: What is keyword auto for?

By default every local variable of the function is automatic (auto). In the below function both the variables 'i' and 'j' are automatic variables.

void f() 
{
   int i;

   auto int j;
}


Q. 69: What is a static variable?

A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.

void f() 
{ 
   static int i; 

   ++i; 
   printf(“%d “,i); 
}

If a global variable is static then its visibility is limited to the same source code.



Q. 70: What is a token?

A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.



Q. 71: What is recursion?

Function calling itself is called as recursion.