Top 50 C++ Advanced Interview Questions

The blog provides the common asked interview questions on C++ advanced programming concepts, interview questions on inline functions in C++, interview questions on new vs malloc() in C++, interview questions on free() vs delete in C++ , interview questions on memory allocation using malloc () , calloc() in C++ , interview questions on void pointer in C++, interview questions on this pointer in C++, interview questions on Constructor in C++, interview questions on Destructor in C++, interview questions on Virtual Destructor in C++, interview questions on Virtual functions in C++, interview questions on static functions in C++,  interview questions on Const Reference Arguments in C++, Interview Questions on preprocessor directives types in C++ , Interview Questions on Name Mangling in C++, Interview Questions on Scope Resolution Operator (::) in C++, Interview Questions on Friend function in C++, Interview Questions on smart pointers in C++, Interview Questions on smart pointers types in C++ and many more

 

C++ advanced programming concepts related questions and answers for the beginners and professionals to prepare for the competitive exams  and IT jobs.

1) Define inline Functions in C++ ? 

The Inline functions in C++ is an feature to increase the overall execution time of the program. The inline functions  in the class inform C++ compiler to consider the function as inline and compiler recompiles all the classes using this inline function and  replaces the definition of inline functions at compile time instead of referring function definition at runtime.

Advantages of Inline Functions in C++ .

  • Inline Functions in C++ enhances program performance by avoiding function calling overhead
  • Inline Functions in C++ reduces the overhead of Push/ Pop in the stack at the time of function calling
  • Inline Functions in C++ reduces the overall return call from a function
  • Inline Functions in C++ makes the variable reference locally by following instruction cache
  • Inline Functions in C++ allows to define the function definition in a header file

Disadvantages of Inline Functions in C++ 

  • Inline Functions in C++ increases the executable size due to code expansion
  • Inline Functions in C++ reduces recompiling every time at the change of code.
  • Inline Functions in C++ definition in header file increases the header size 
  • Inline Functions in C++ with large executable size are not recommended for embedded system due to memory constraints

Inline function Syntax  in C++ 

inline return-type function-name(parameters)
{
    // function code
}  

Inline function example in C++ 

#include <iostream>
using namespace std;
//define inline function for adding 2 numbers
inline int Addition(int numeric1, int numeric2) {
return (numeric1 + numeric2);
}

// program main function() calling
int main() {
cout << "Addition (18,10): " << Addition(18,10) << endl;
cout << "Addition (20,20): " << Addition(20,20) << endl;
cout << "Addition (5,5): " << Addition(5,5) << endl;

return 0;
}

2) What is the difference between new  and malloc() in C++ ?

  • Both new and malloc() are used to allocate memory but malloc() is a C programming library function of stdlib.h which can be used in C++ also for memory allocation to N Blocks at run -time whereas new is an operator specific to C++ programming for memory allocation at run -time.
  • Both new  and malloc () allocates memory dynamically in heap but new calls the class constructor for object initialization whereas malloc() does not
  • new returns the specific data type whereas malloc() return type is void*
  • new as an operator is faster than malloc () as a function
  • new when allocates memory initializes it to 0 whereas malloc() when allocates memory initializes with random value
  • new memory allocation is calculated by compiler whereas for malloc() memory allocation developers need use sizeof()
  • malloc () memory allocation can be changed using realloc() where new memory allocation can’t

malloc() and new memory allocation example in C++

int *mallocvar; //pointer declaration
//allocate memory using malloc for 5 integers
mallocvar = (int*) malloc(sizeof(int)*5);
int *mallocvar; //pointer declaration
//allocate memory using new for 5 integers
mallocvar = new int[5];

3) What is the difference between free() and delete in C++ ?

  • Both free()  and delete  are to de-allocate the memory dynamically but free() is a C programming library function of stdlib.h which can be used in C++ also to de-allocate memory whereas delete is an operator specific to C++ programming to free the run time allocated memory.
  • delete de-allocates the memory and calls the destructor whereas free() de-allocates the memory but doesn’t call destructor
  • free() releases the memory allocated by malloc() and delete and delete [] releases memory allocated to array and non-array objects using new operator
  • free() uses run-time heap whereas delete use private heap based on overloaded class basis
  • delete as an operator is faster than free() as a function
  •  

free() example in C++ using calloc() . The calloc() assing the memory to *ptr and fee() releases the allocated memory

#include <iostream> 
#include <cstdlib>
using namespace std;
int main()
{
float *ptr; // float pointer declaration
ptr=(float*)calloc(1,sizeof(float));
*ptr=8.2;
std::cout << " *ptr before free() : " <<*ptr<< std::endl;
free(ptr);
std::cout << "*ptr after free() :" <<*ptr<< std::endl;
return 0;
}

delete example in C++ using new operator.

#include <iostream> 
#include <cstdlib>
using namespace std;

int main()
{
int *ptr;
ptr=new int;
*ptr=24;
std::cout << " ptr before delete : " <<*ptr<< std::endl;
delete ptr;
std::cout <<" ptr after delete : " <<*ptr<< std::endl;
return 0;
}

4) A memory allocated using new can be deallocated using free() in C++ ?

A new operator in C++ allows to create the memory and calls the constructor to point he memory location in heap. The memory deallocated using the free() then the object dies but the memory allocated leaks out as free() does not call the destructor for memory deallocation from the heap.

5) What are the possible ways of exporting a function from DLL in C++ ?

DLL stands for Dynamic Link Library in C++. The below given methods can be used for exporting a function from DLL

  • using Dynamic Link Library (DLL) type library
  • using an reference of the function from the DLL instance

6) Define destructor in C++ ?

  • A destructor is used to release the allocated memory for data members and class object. 
  • A destructor gets called automatically whenever an objects goes out of the scope.
  • A destructor could have the same name as class name preceded by tilde
  • A destructor does not contain any parameters or return type

7) What is pointer in C++ ?

The pointer in C++ allows to hold the address of the variable memory allocation. The pointer can be assigned with data type such as integer , char, long , float.

Syntax:  data type <pointer-name>

Pointer example in C++ 

// define a integer pointer ptr and a variable
int
*ptr, var
//assign address of variable to pointer ptr
ptr = &var;
//print the address for ptr which should be same as variable address
cout<<*ptr;

8) What is ‘this’ pointer in C++ ?

Each class in C++ is referenced through an object which is a collection of class member ( variables and functions). In case the same class members are being invoked by multiple objects, then how to ensure that the exact data members are accessed and updated when the local variable name is same as data member name. 

‘this’ pointer in C++ provides the reference of the data member being referenced for all the non-static members of the class and thus helps in updating the memory allocation of the data member. 

‘this’ pointer example in C++ 

#include<iostream> 
using namespace std;

/* local variable is same as a member's name */
class Thisexample
{
private:
int numeric1;
public:
void setX (int numeric1)
{
// The 'this' pointer retrieves the numeric1 object reference
this->numeric1 = numeric1;
}
void print() { cout << "numeric1 = " << numeric1 << endl; }
};

int main()
{
Thisexample obj;
int numeric1 = 20;
obj.setX(numeric1);
obj.print();
return 0;
}

9) What is ‘void’ pointer in C++ ?

A void pointer is a pointer that has no associated data type and can hold address of any data type and can be type casted to any data type.

int main (void) {
int m = 21;
char n = 'dummy';
void *p = &m; // this assigns address of int 'm' to void pointer
p = &n; // Updates the address of 'n' to void pointer

cout << "value of void p = " << *p << endl; // prints the address of 'n'
}

malloc() and calloc() functions are with return type as Void* and thus these functions are used to allocate memory to any data type. 

int main(void) 
{
       int *x = malloc(sizeof(int) * n);
}

10) What is a Virtual Function in C++ ?

  • A Virtual function is a base class member function which can be overridden by the derived class
  • A Virtual function is declared with a Virtual keyword in the base class
  • Non-member functions and static member functions cannot be virtual
  • Virtual functions cannot have any associated constraints
  • If a function is defined with specifier final , then it cannot be called by another function
  • Virtual functions are accessed using pointer or base class reference to achieve run time polymorphism
  • The member function of the derived class should have the same name , same parameters as Base Class Virtual function

Virtual Function example in C++ 

class Baseclass {
virtual void execute(); // private member
public:
void func() { execute(); } // public interface
};
struct Derivedclass: public Baseclass {
void execute() override; // overrides Baseclass::execute
};

int main()
{
Derivedclass dc;
Baseclass* bc = &dc;
bc->func(); // internally calls Derivedclass::execute();
}

11) Does Virtual Constructor supported in C++ ?

The Virtual Constructor in C++ is not possible. 

Usually the data members of the class can be Virtual as the hidden table for the function pointer also called as vtable is actually the data member of an object which makes the members virtual. Thus, when a constructor is invoked for the specific class , then at time there is no virtual pointer defined and thus virtual constructor cannot be created. In others words, we can say that a constructor in C++ is always non-virtual.

12) What is a Virtual Destructor in C++ ?

A destructor is used to deallocate the memory consumed by the data member or to delete the class object when the class is out of scope whereas the Virtual Destructor in C++ is used to release the memory allocated to the derived class data members and derived class object. The Virtual Destructor uses the base class pointer object while deleting the derived class instance.

If the base class object gets out of the scope then only the base class object gets destroyed and the associated derived class objects gets ignored and thus adds to memory leak. To avoid this , the derived class contains the virtual destructor pointing to base class and thus initiates the derived class destructor before the base class gets out of the scope which finally avoid memory leaks.

13) What is pure virtual function in C++ ? 

  • The function with no function definition are called as “do- nothing” or pure virtual function
  • The class containing the pure virtual function are considered as abstract classes and cannot be initiated
  • The abstract class having pure virtual function allows derived class to create the base pointer for achieving the run-time polymorphism

14) Can a Destructor be a Pure Virtual Destructor in C++ ? 

  • Yes, the destructor in the Base Class can be considered as Pure Virtual Destructor
  • The base class should have the function body for the Pure Virtual Destructor as destructor are not overridden rather called in the reverse order and thus derived class destructor will be invoked first.
  • The base class containing the Pure Virtual Destructor are considered as abstract class and cannot be initiated

15) Can static functions be Virtual in C++ ? 

The static member function of the class in C++ cannot be considered as Virtual

16) What is the pointer size in C++ ?

The pointer size varies based on the platform where the C++ program is executed 

                  System Pointer Size 
 16-bit system 2 bytes
 32-bit system 4 bytes
 64-bit system 8 bytes

17) Is it safe to delete a void pointer in C++ ?

The void pointer is not associated to any data type and thus can be type casted to any data type. Due to this reason, it is not considered safe to delete the void pointer in C++ , as to destroy the object it requires to call the destructor of the object and that is not feasible as void pointer does not know the data type

18) What is pointer operator (&) in C++ ? 

The pointer in C++ allows to hold the address of the variable memory allocation. The pointers can further be divided into 2 types of pointer operators as given below:

  • Address of Operator (&) :  In Address of Operator type, a pointer as a variable holds the address of the other variable which could be type object, structure or pointer itself . 
  • Indirection Pointer (*) : In Indirection pointer type, a pointer as a unary operator returns variable value associated with the address provided by its operand.

Pointer Operator example in C++ 

#include <iostream>
using namespace std;
int main () {
int xyz;
int *ptr;
int output;
xyz = 101;

// ptr contains the address for xyz
ptr = &xyz;

// output contains the ptr value
output = *ptr;
cout << "xyz :" << xyz << endl; //prints the value of xyz as 101
cout << "ptr :" << ptr << endl; // prints the address for xyz
cout << "output :" << output << endl; //prints the value of output as 101 which is same as xyz
return 0;
}

19) Difference between references and pointers in C++ ?

The below given are the major differences between the references and pointer in C++

Pointers in C++ Reference in C++ 
Pointer in C++ allows to hold the address of the variable memory allocationReference is an alias for an existing variable
Pointer can be assigned with NULL valueReference variable cannot be assigned with NULL 
Pointer does not require to be initialized at the time of declarationReference variable need to be initialized when declared
Pointer requires Indirection operation (*) to access the valueReference variable are accessed directly
Pointer variable can be re-assigned multiple time Reference variable once assigned cannot be changed

20) What is Stack unwinding in C++ ?

Stack unwinding is a process in which a specific program invokes the destructor for destroying all the local objects in the stack between throwing and catching of an exception.

21) What is Const Reference Arguments and its advantages in C++ ?

C++ allows to declare a reference to a const value. This can be achieved by declaring a reference using the const keyword. A reference to a const value can reference a non-const variable.

int a{3};
const int& ref1{ a }; // a is a non-const value

const int b{ 2 };
const int& ref2{ b }; // b is a const value

Below given are the advantages of using cosnt reference arguments in C++ 

  • Allows to process the const and non-const arguments by the function
  • Allows the generation and usage of a temporary variable by the function appropriately
  • Protects against errors that result due to data change

22) What is a class template in C++ ? 

 

23) Difference between a macro and a template ?

Macros in C++Template in C++
A macro is declared using #define directive to provide meaningful identifiers with statements or expressions. When the name of a macro is recognized in the program or in the arguments of preprocessor commands, preprocessor replaces the macros in the form of string in the source code with values derived from the macro definition.A template allows to create generic functions that receives any data type as parameters and return a value without any data type
A macro cannot call itselfA template can call itself

Macro definition in C++ 

#include <stdio.h> 

// macro definition
#define MAXCOUNT 5
int main()
{
for (int i = 0; i < MAXCOUNT; i++) {
printf("%d \n",i);
}
return 0;
}

24) What are the types of preprocessor directives in C++ ?

There are 4 types of preprocessor directives in C++

  • Macros
  • File Inclusion
  • Conditional Compilation
  • Other directives

25) What is Name Mangling in C++ ? 

Name Mangling in C++ is the technique which helps in encoding the functions and variable names into unique names. The C++ compiler also mangles C variable names to identify the namespace in which the C variable resides. The name mangling becomes more important at compiler level as C++ uses the ‘C’ language libraries and it is required to distinguish to identify which functions needs to be called. 

26) Explain Scope Resolution Operator (::) in C++ ?

The scope resolution(::) operator in C++ helps in accessing the member functions outside the class. For instance a class is having same name (var) for the local variable in the function and a global variable at class level, then using ::var the global variable value can be accessed.

The scope resolution can be used at class level also to get the global variables accessed

The scope resolution also helps to bypass the override of a base class member that a derived class has overridden

27)  What is the disadvantages of Friend function in C++ ?

The friend function gets the access for all the class member functions ( variables and functions) and thus extensive usage of friend function in the programs violates the encapsulation and thus be used in restricted mode.

28)  Give some examples of operator overloading in C++ ?

  • Operator Overloading can be used to concatenate 2 string using + operator
  • Operator Overloading can be used to increment the date using ++ operator
  • Operator Overloading can be used to multiply 2 numbers using * operator
  • Operator Overloading can be used to access array elements using subscript operator

29) Difference between Const Int *ptr and Int Const *ptr in C++ ?

Const int *ptr is a pointer declaration to const int object which cannot be changed using a pointer

int Const * ptr is a pointer declaration is a const pointer to an int object and can be changed using a pointer 

30) What are smart pointers in C++ ? 

If the developers does not manage the destruction of objects which are out of scope or improper handling of object release leads to memory leaks.  C++ 11 provides smart pointers which automatically manages memory and deallocates the object when the pointer becomes out of scope.

Smart pointers are defined in the std namespace in the <memory> header file

31) What are the types of smart pointers in C++ ? 

The smart pointers in C++ can be classified into 3 categories

  • unique_ptr: unique_ptr allows to define one owner for the underlying pointer and is the repalcement for auto_ptr which is deprecated.  The size for unique_ptr is 1 pointer and allows rvalue references for fast insertion and retrieval from the C++ Standard Library collections
  • shared_ptr: shared_ptr allows to assign 1 pointer to multiple pointers / owners . The size for shared_ptr is 2 pointer, the 1 for the object and 1 for the shared control block  that contains the reference count. For instance , the return copy of a pointer returns the copied pointer and reference of the original pointer.
  • weak_ptr : weak_ptr allows access to an object that is owned by one or more shared_ptr instances. weak_ptr is useful when it is required to observe an object, but do not require it to remain alive

32) Give example of unique_ptr in C++ ?

  • std::unique_ptr is a lightweight smart-pointer helps in creating the dynamically allocated objects.
  • A unique_ptr deallocates the object by calling delete
  • A unique_ptr deallocates array object by calling delete []
struct Students { };

void getStudents() {
// create dynamic array object using std::unique_ptr
auto students[] = std::unique_ptr<Students[]>(new Students[30]);
}

The unique_ptr proivdes the overloaded operator [] to access the array elements

 // using std::unique_ptr<T[]> for accessing array elements
auto students = std::get_students<int[]>(30);
for(int incr=0; incr < 10; incr++)
students[incr] =incr;

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*