c++interview questions

C++ Interview Questions and Answers(2024)

This article is mainly focused on the most repeatedly asked and the latest updated C++ interview questions that are appearing in most of the current C++ interviews.

C++ is a powerful and general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language. C++ is standardized by the ISO (International Organization for Standardization) and they revise and publish the new version from time to time.

Some real-world applications where C++ is widely used

  • CAD Software.
  • Game Development.
  • GUI-based applications.
  • Operating systems
  • Banking applications.
  • Advanced computations and graphics.
  • Embedded systems.
  • Database software.

If you are looking for “C++ interview questions” or  “advanced C++ interview questions, then you are at the right place. Here I have tried to create a collection of “C++ interview questions with answers” that might ask by your interviewer. These C++ interview questions are not only for fresher but also good for the experienced person.

We have categories these C++ Questions into three parts basic, intermediate and advanced. I hope these free C++ interview questions with the answer will be helpful for your next job. If you want to add more questions related to  C++ programming and concept or want to give the answer to any mentioned C++ interview questions, then please write in the comment box. It is helpful to others.

 

C++ Interview Questions For Freshers:

 

Q) Define C++?

C++ is a high-level, general-purpose programming language created by “Bjarne Stroustrup” as an extension of the C programming language, or “C with Classes”. The language has expanded significantly over time, and modern C++ has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.

 

Q) What is the difference between C and C++?

The below comparison chart explain some important difference between C and C++.

C C++
C is a structural or procedural programming language. C++ is an object-oriented programming language.
 C doesn’t have variable references. C++ has variable references.
C doesn’t support function or operator overloading C++ supports function as well as function overloading.
C does not support information hiding. Data is hidden by Encapsulation to ensure that data structures and operators are used as intended.
“namespace” features are not present in C. “namespace” is used by C++, which avoids name collisions.
Virtual and friend functions are not supported by C. Virtual and friend functions are supported by C++.
In C, functions can not be defined inside structures. In C++, we can define functions inside structures.
C doesn’t provide direct support for error handling C++ supports exception handling that helps in error detection and smooth handling.
C uses malloc(), calloc() for memory allocation and  free() for memory de-allocation . In C++, generally, “new operator” is used for memory allocation, and deletes operator is used for memory deallocation.
C does not support inheritance. C++ supports inheritance.
C does not support generic programming. C++ supports generic programming with the help of templates.

 

Q) What is a class in C++?

A class in C++ is a user-defined type declared with a keyword class that has data and functions (called member variables and member functions).

Example,

class Test
{
   // some data
   // some functions
};

Access of class members is governed by the three access specifiers private, protected, and public. By default access to members of a C++ class is private.

 

Q) What is an object?

An object is an instance of a class through which we access the methods and attributes of that class.

 

Q) Why use access modifiers in C++?

Access modifiers are an integral part of object-oriented programming. They are used to implement the encapsulation of OOP. The access modifiers allow you to define who does or who doesn’t have access to certain features.

 

Q) What are C++ access modifiers?

C++ supports three access specifiers that you can use to define the visibility of classes, methods, and attributes.

public: There are no restrictions on accessing public members. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.

class Test
{
public:
    //Access by anyone
    int data;
};

 

Private: Access is limited to within the class definition. This is the default access modifier type for a class if none is formally specified. They are not allowed to be accessed directly by any object or function outside the class.

class Test
{
private:
    // Access only by member functions 
    //and friends of that class
    int data;
}

 

Protected: Access is limited to within the class definition and any class that inherits from the class.

class Test
{
protected:
    //Access by member functions and friends of that class,
    //and by member functions and friends of derived classes.
    int data;
};

 

Q) What are the differences between a class and a structure in C++?

In C++, technically, the difference between the struct and class is that the struct is public by default and the class is private. Generally, we use the struct to carry the data. See the below comparison chart for struct and class, for more detail you can check the article, struct vs class in C++.

Structure Class
By default member variables and methods of the struct is public. By default member variables and methods of the class is private.
When deriving a struct, the default access specifier is public. When deriving a class, default access specifiers are private.

Let see two example codes to understand the difference between struct and class.

Example-1:

#include <iostream>
using namespace std;

class Test
{
    int x; // Default: x is private
};

int main()
{
    Test t;
    
    t.x = 20; // compiler error because x is private
    
    return 0;
}

Output: error: ‘int Test::x’ is private|

Example-2:

#include <iostream>
using namespace std;


struct Test
{
    int x; // Default: x is public
};

int main()
{
    Test t;

    t.x = 20; // No compiler error because x is public

    cout << t.x;

    return 0;
}

Output: 20

 

Q) Why is the size of an empty class not zero in C++?

The standard does not allow objects of size 0 since that would make it possible for two distinct objects to have the same memory address. That’s why even empty classes must have a size of (at least) 1 byte.

Example,

#include<iostream>
using namespace std;

class Test
{
 //empty class
};

int main()
{
    cout << sizeof(Test);

    return 0;
}

Output: 1

 

Q) What is a constructor?

Class constructors in C++  are special member functions of a class and it initializes the object of a class. It is called by the compiler (automatically) whenever we create new objects of that class. The name of the constructor must be the same as the name of the class and it does not return anything.

You should remember that the constructor has a secret argument and this argument is “this pointer” (Address of the object for which it is being called).

 

Q) Is the default constructor exists in C++?

If you will not create your own constructor, then yes compiler will create a default constructor for you.

 

Q) What are the various OOPs concepts in C++?

Below we are mentioning a few fundamental OOP (Object Oriented Programming) concepts:

  • class.
  • object.
  • Inheritance.
  • Polymorphism.
  • Encapsulation
  • Abstraction.

 

Q) What is polymorphism in C++?

The word polymorphism is a Greek word that means “many-form“. So polymorphism in C++ means, the same entity (method or object) behaves differently in different scenarios. Let’s consider a real-life example of polymorphism. A man behaves like an employee in the office, a father, husband, or son in a home, and a customer in a market. So the same man possesses different behavior in different situations. This is called polymorphism. We can categorize polymorphism into two types. These are Compile-time polymorphism and Run-time polymorphism.

 

Q) What are the different types of polymorphism in C++?

In C++ polymorphism is mainly divided into two types:

  1. Compile-time Polymorphism.
  2. Runtime Polymorphism.

Polymorphism in c++

 

Q) Compare compile-time polymorphism and Run-time polymorphism?

The following table describes the basic difference between compile-time polymorphism and run-time polymorphism.

Compile-time polymorphism Run time polymorphism
The function called resolved at the compile time. The function called resolved at the run time.
It is also known as overloading, early binding, and static binding. It is also known as overriding, Dynamic binding, and late binding.
Inheritance is not required for compile-time polymorphism. Inheritance is required for compile-time polymorphism.
It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.
The virtual keyword is not involved here. The virtual keyword plays an important role here.
It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.

 

Q) What is encapsulation?

Containing and hiding Information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object’s operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data’s origin.

 

Q) What Is Inheritance?

Inheritance allows us to create a new class (derived or child class) from an existing class (base or parent class). The class whose members are inherited is called the base or parent class, and the class that inherits those members is called the derived or child class.

Example,

Class Cow, Class Dog, and Class Cat inherit the properties of Class Animal. And you can see the is-a relations ship between the Base class (Animal) and Derived classes (Cow, Dog, and Cat).

Inheritance in cpp

 

Q) What are the advantages of inheritance?

There are many benefits of inheritance in C++, so let us see them:

  • Inheritance provides code reusability, makes it easier to create and maintain an application. So we don’t have to write the same code again and again.
  • It allows us to add more features to a class without modifying it.
  • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
  • Inheritance represents real-world relationships well.

 

Q) What is an abstraction in C++?

Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and hiding the details. Data.

Consider a real-life scenario, Suppose you booked a movie ticket from BookMyShow using net banking or any other process. You don’t know the procedure of how the pin is generated or how the verification is done. This is called ‘abstraction’ from the programming aspect, it basically means you only show the implementation details of a particular process and hide the details from the user.

Note: An abstract class cannot be instantiated which simply means you cannot create objects for this type of class. It can only be used for inheriting the functionalities.

 

Q) What is a reference in C++?

reference defines an alternative name for an object or you can say that it is an alias of a referring object. In programming, we define the reference of an object by using the & with followed by the reference name.

Example,

//create an variable
int data = 6;


//rOffData refer to data
int& rOffData = data;

You can read the post “Reference in C++ with programming examples“.

 

Q) What is the default constructor?

A constructor without any arguments or with the default value for every argument is said to be a default constructor.

 

Q) What is a destructor in C++?

A destructor is a member function that destructs or deletes an object.

 

Q) When is the destructor called?

A destructor is called automatically when the object goes out of scope:

  • At the function ends.
  • When the program ends.
  • A block containing local variables ends.
  • When the delete operator is called.

 

Q) Is it possible to overload the destructor of the class?

No. You can not overload the destructor of the class. You can’t pass parameters to the destructor anyway, so there’s only one way to destroy an object.

 

Q) Should I explicitly call a destructor on a local variable?

No. Destructor invokes automatically when the local variable is destroyed. But might be you will get bad results from calling a destructor on the same object a second time!.

 

Q) How destructors are different from a normal member function.

The name of the destructors must be the same as the class name preceded by a tilde (~). Also, destructors don’t take any argument and don’t return anything.

 

Q) What is the difference between constructor and destructor?

There are the following differences between the constructor and destructor in C++.

Constructor Destructor
Constructor helps to initialize the object of a class. Whereas destructor is used to destroy the instances.
The constructor’s name is the same as the class name. The destructor name is the same as the class name but preceded by a tiled (~) operator.
A constructor can either accept the arguments or not. While it can’t have any argument.
A constructor is called when the instance or object of the class is created. It is called while the object of the class is freed or deleted.
A constructor is used to allocate the memory to an instance or object. While it is used to deallocate the memory of an object of a class.
A constructor can be overloaded. While it can’t be overloaded.
There is a concept of copy constructor which is used to initialize an object from another object. While here, there is no copy destructor concept.

 

Q) What is “this” pointer?

The “this pointer” is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have this pointer. When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function.

An object’s this pointer isn’t part of the object itself. It’s not reflected in the result of a sizeof statement on the object.

Note: The friend functions also do not have this pointer, because friends are not members of a class.

 

Q) Where we should use this pointer in C++?

There are a lot of places where we should use this pointer. Below I am mentioning some scenarios where you should use this pointer, so let see.

1. When the local variable’s name is the same as the member’s name?

 

#include<iostream>
using namespace std;
class Test
{
private:
    //member variable
    int x;
public:
    void setX (int x) //x is local
    {
        // The 'this' pointer is used to retrieve the object's x
        // hidden by the local variable 'x'
        this->x = x;
    }
    void DisplayX()
    {
        cout << "x = " << x << endl;
    }
};
int main()
{
    Test obj;
    int x = 20;
    obj.setX(x);
    obj.DisplayX();
    return 0;
}

 

2. To return a reference to the calling object.

/* Reference to the calling object can be returned */
Test& Test::func ()
{
   // Some processing
    return *this;
}

 

3. When needs chain function calls on a single object.

#include<iostream>
using namespace std;

class Test
{
private:
    int x;
    int y;
public:
    Test(int x = 0, int y = 0)
    {
        this->x = x;
        this->y = y;
    }
    Test &setX(int a)
    {
        x = a;
        return *this;
    }
    Test &setY(int b)
    {
        y = b;
        return *this;
    }
    void print()
    {
        cout << "x = " << x << " y = " << y << endl;
    }
};

int main()
{
    Test obj(7, 7);

    obj.print();

    // Chained function calls. All calls modify the same object
    // as the same object is returned by reference

    obj.setX(10).setY(20).print();

    return 0;
}

Output:

x = 7 y = 7
x = 10 y = 20

 

Q) What is a “new” keyword in C++?

In C++, “new” is an operator. It allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.

You can read my blog post “Learn the uses of the new operator with C++ programming example“.

 

Q) What is the difference between new and malloc?

See the following comparison chart for malloc and new (malloc vs new):

Feature new malloc
Supported language C++ specific features Supported by both C and C++
Type new is an operator that takes a type and (optionally) a set of initializers for that type as its arguments. malloc() is a library function that takes a number (of bytes) as its argument.
Returns Returns a pointer to an (optionally) initialized object of its type which is type-safe. It returns a void* pointing to uninitialized storage which is type unsafe.
On failure It throws bad_alloc exception on failure. Returns NULL
Required size Calculated by compiler Must be specified in bytes
Handling arrays Has an explicit version Requires manual calculations
Use of constructor Yes. Operator new call the constructor of an object. No
Overridable Yes. No
Deallocation memory allocated by malloc() is deallocated by free(). Objects created by new are destroyed by delete.
Initialization The operator new could initialize an object while allocating memory to it. The malloc returns an uninitialized block of memory.

You can check my blog post “malloc vs new” which describes the difference between malloc and new with the help of programming examples.

 

Q) What is the difference between delete and free?

First, let see what is the ‘delete’ and ‘free’ in C++, then we will see the difference between them.

Delete:

Delete is an Operator in C++ which is used to free the memory allocated by the ‘new’ operator. It is also called the destructor of the class.

The following is the general syntax of delete expression.

1. ::opt delete cast-expression

2. ::opt delete [ ] cast-expression

1. Destroys one non-array object created by a new-expression.

2. Destroys an array created by a new[]-expression

 

Free():

A free function is used to deallocate memory allocated by the malloc() or calloc() function.

The general syntax to use free:

free(ptr);

Some differences between delete and free:

  • ‘delete’ is an operator while ‘free’ is a function.
  • ‘delete’ frees the allocated memory which allocates by new and free frees the memory allocated by malloc, calloc, realloc.
  • ‘delete’ calls the destructor while free does not call any destructor.
  • free() uses C run time heap whereas delete may be overloaded on a class basis to use private heap.

 

Q) What do you mean by call by value and call by reference?

You can pass the value in function two ways call by value or call by reference. These two ways are generally differentiated by the type of values passed to them as parameters.

Call by value-: Values of actual parameters are copied to the function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller.

Call by reference-: Addresses of the actual arguments are copied and then assigned to the corresponding formal arguments. So in the call by reference both actual and formal parameters are pointing to the same memory location. Therefore, any changes made to the formal parameters will get reflected in the actual parameters.

To get more knowledge, you can read this post ” Call by value and Call by reference“.

 

Q) What is a namespace?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your codebase includes multiple libraries.

Syntax of the namespace:

namespace Name_namespace
{
  named_entities
}

 

Q) How to use namespace in C++?

Let us see a namespace “Test”,

namespace Test
{
    class TestObject
    {
    public:
        void DoSomething() {}
    };
    void Func(TestObject) {}
}

Now let see three ways to access the members of the namespace “Test”.

1, Use the fully qualified name:

Test::TestObject test;

test.DoSomething();

Test::Func(test);

2. Use a using-declaration to bring one identifier into scope:

using Test::TestObject;

TestObject test;

test.DoSomething();

 

3. Use a using directive to bring everything in the namespace into scope:

using namespace Test;

TestObject test;
test.DoSomething();
Func(test);

 

Q) What is a member function in C++?

A member function of a class is a function that has its definition or its prototype within the class definition.

 

Q) What are static members in C++?

We are breaking this question into three-part because a static keyword has an important role in C++.

member variable as static (static member variable):

The static keyword allows a variable to maintain its value among different function calls. The value of static variable changes when the variable has been accessed, the variable keeps the new value. If the same variable gets accessed again, it would be holding its most recent value. This is possible because, when the static variable is declared, the compiler uses a separate memory area to store it (BSS or DS). By doing this, when the value of the static variable gets changed, it is updated in the memory it is occupying. And because this memory is separate, the compiler can monitor its values even when its function exits.

function as static (static member functions):

There are some points related to the static function.

  • A static member function can access only static member data, static member functions and data and functions outside the class.
  • A static member function can be called, even when a class is not instantiated.
  • A static member function cannot be declared virtual.
  • A static member function cannot have access to the ‘this’ pointer of the class.
  • A static member function does not have this pointer, so there is no meaning of using a CV qualifier (const, volatile, const volatile) with static member function because the cv-qualifier modifies the behavior of ‘this’ pointer.

destructor as static:

A “static destructor” is a static member function of the class that accepts one argument a pointer to the object of that class to be destroyed. It is probably used along with “a factory method”. When there is a need to restrict the creation of instances of some class to free store only and/or perform additional steps before or after the creation of an object. Similar steps may need to be taken before and/or after destroying an instance.

 

Q) What do you mean by inline function and How to implement the inline function in C++?

The inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler’s discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline.

Syntax of inline function,

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

 

Q) What is the use of the inline function in C++?

The use of inline functions generates faster code and can sometimes generate smaller code than the equivalent function call generates for the following reasons:

  • It saves the time required to execute function calls.
  • Small inline functions, perhaps three lines or less, create less code than the equivalent function call because the compiler doesn’t generate code to handle arguments and a return value.
  • Functions generated inline are subject to code optimizations not available to normal functions because the compiler does not perform interprocedural optimizations.

 

Q) What is the advantage and disadvantage of the inline function?

There are a few important advantages and disadvantages of the inline function.

Advantages:-

1) It saves the function calling overhead.
2) It also saves the overhead of variables push/pop on the stack, while function calling.
3) It also saves the overhead of return call from a function.
4) It increases the locality of reference by utilizing the instruction cache.
5) After the inlining compiler can also apply intraprocedural optimization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination, etc..

Disadvantages:-

1) May increase function size so that it may not fit in the cache, causing lots of cache miss.
2) After inlining function, if variables numbers which are going to use register increases than they may create overhead on register variable resource utilization.
3) It may cause compilation overhead as if somebody changes code inside an inline function then all calling locations will also be compiled.
4) If used in the header file, it will make your header file size large and may also make it unreadable.
5) If somebody used too many inline functions resultant in a larger code size than it may cause thrashing in memory. More and number of page faults bringing down your program performance.
6) It’s not useful for an embedded system where large binary size is not preferred at all due to memory size constraints.

 

Q) What’s the difference between static, inline, and void with functions?

static:

static means it can’t be called from another compilation unit (source file) by name. But using function pointer forcibly you can call.

inline:

An inline keyword is a compiler directive that only suggests the compiler to substitute the body of the function at the calling the place. It is an optimization technique used by the compilers to reduce the overhead of function calls. The compiler does not inline a function if its address is taken or if it is too large to inline.

void:

void means the function does not return a value.

 

Q) What is function overloading in C++?

With the C++ language, you can overload functions and operators. A function Overloading is a common way of implementing polymorphism. Overloading is the practice of supplying more than one definition for a given function name in the same scope. A user can implement function overloading by defining two or more functions in a class sharing the same name. C++ can distinguish the methods with different method signatures (types and number of arguments in the argument list).

Note: You cannot overload function declarations that differ only by return type

 

Q) Explain some ways of doing function overloading in C++?

Function overloading can be done by changing:

1.The number of parameters in two functions.

#include <iostream>
using namespace std;

void Display(int i, char const *c)
{
    cout << " Here is int " << i << endl;
    cout << " Here is char* " << c << endl;
}

void Display(double f)
{
    cout << " Here is float " << f << endl;
}

int main()
{
    Display(5,"Five");
    
    Display(5.5);
    
    return 0;
}

Output:

Here is int 5
Here is char* Five
Here is float 5.5

 

2. The data types of the parameters of functions.

#include <iostream>
using namespace std;

void Display(int i)
{
    cout << " Here is int " << i << endl;
}

void Display(double f)
{
    cout << " Here is float " << f << endl;
}

void Display(char const *c)
{
    cout << " Here is char* " << c << endl;
}

int main()
{
    Display(5);
    
    Display(5.5);
    
    Display("Five");
    
    return 0;
}

Output:

Here is int 5
Here is float 5.5
Here is char* Five

 

3. The order of the parameters of functions.

#include <iostream>
using namespace std;

void Display(int i, char const *c)
{
    cout << " Here is int " << i << endl;
    cout << " Here is char* " << c << endl;
}

void Display(char const *c,int i)
{
    cout << " Here is int " << i << endl;
    cout << " Here is char* " << c << endl;
}

int main()
{
    Display(5,"Five");
    
    Display("Five",5);
    
    return 0;
}

Output:

Here is int 5
Here is char* Five
Here is int 5
Here is char* Five

 

Q) What is operator overloading?

Operator overloading allows you to redefine the functionality of the allowed operators, such as “+”, “-“, “=”, “>>”, “<<“. You can say that operator overloading is similar to function overloading.

Example,

In the below example I am overloading the + operator to add the two objects of the “Test class” and return the result and print the same. If you don’t know the operator overloading you can read this post for more information, “Operator Overloading in C++ with some FAQ“.

#include <iostream>
using namespace std;

//class Test
class Test
{
public:
    //constructor
    Test( int data1, int data2 ) : m_data1(data1), m_data2(data2) {}
    //overloaded + operator
    Test operator+( Test &rObj);
    //print the value
    void print( )
    {
        cout << "m_data1 = " << m_data1 <<endl;
        cout << "m_data2 = " << m_data2 << endl;
    }
private:
    //member variables
    int m_data1,m_data2;
};


// Operator overloaded using a member function
Test Test::operator+( Test &rObj )
{
    return Test( m_data1 + rObj.m_data1, m_data2 + rObj.m_data2 );
}


int main()
{
    Test obj1(1,2);
    Test obj2(5,6);
    Test obj3(0,0);

    //adding two object of class Test
    obj3 = obj1 + obj2;

    //print the result of addition
    obj3.print();

    return 0;
}

Output:

m_data1 = 6
m_data2 = 8

 

Q) What is the difference between function overloading and Operator Overloading?

Operator overloading allows operators to have an extended meaning beyond their predefined operational meaning. Function overloading (method overloading) allows us to define a method in such a way that there are multiple ways to call it.

 

Q) What is the assignment operator in C++?

The default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy). If required we can overload the assignment operator.

 

Q) Can you overload a function based only on whether a parameter is a value or a reference?

No, We can not overload a function based only on whether a parameter is a value or a reference. Because passing by value and by reference looks identical to the caller.

 

Q) What is Overriding?

Overriding a method means that replacing a function functionality in child class. To imply overriding functionality we need parent and child classes. In the child class, you define the same method signature as one defined in the parent class.

In simple words, when the base class and child class have member functions with exactly the same name, same return type, and same parameter list, then it is said to be function overriding.

Condition for the function overriding is:

  • Must have the same method name.
  • Must have the same data type.
  • Must have the same argument list.

 

Q) Write a C++ program that describes function Overriding?

Let see a program, in which base and child class have the same function Display that follows function overriding rule.

// Function Overriding
#include<iostream>
using namespace std;

//Base class
class BaseClass
{
public:
    virtual void Display()
    {
        cout << "In Base class\n";
    }
};


//child class
class DerivedClass : public BaseClass
{
public:
    // Overriding method - new working of
    // base class's display method
    void Display()
    {
        cout << "In Child class\n";
    }
};

int main()
{
    DerivedClass dr;

    BaseClass &bs = dr;

    bs.Display();
}

Output:

In Child class

 

Q) What is the difference between function overloading and Overriding?

There are some differences between function Overloading and Overriding.

  •  Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance.
  • Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be the same.
  • Overridden functions are in different scopes; whereas overloaded functions are in the same scope.
  • Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have the same name functions that behave differently depending upon parameters passed to them.

 

Q) How to create and use a reference variable in C++?

Let see an example, where I am creating an integer variable and assigning 6 to it. In the second step, I am creating an integer reference and initializing it by data. Now you can see when I am changing the value of the reference, the value of the data is also changing.

#include <iostream>
using namespace std;

int main()
{
    //create an variable
    int data = 6;

    //rOffData refer to data
    int& rOffData = data;

    //print data and rOffData
    cout <<"rOffData = "  << rOffData << endl ;
    cout <<"data = "  << data << endl ;

    // Assign 27 to the rOffData
    rOffData = 27;

    //print data and rOffData
    cout << "After change value of rOffData" << endl;
    cout <<"rOffData = "  << rOffData << endl ;
    cout <<"data = "  << data << endl ;

    return 0;
}

Output:

references in c++

 

Q) What is the difference between a pointer and a reference?

A reference must always refer to some object and, therefore, must always be initialized. Pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.

You can read this post “reference vs pointer“. In which I  have explained the difference between pointer and reference with the help of programming examples.

 

Q) What is the virtual function?

When derived class overrides the base class function by redefining the same function. If a client wants to access redefined the method from derived class through a pointer from the base class object, then you must define this function in the base class as a virtual function.

Let see an example, where the derived class function is called by base class pointer using virtual keyword.

#include<iostream>
using namespace std;

//Base class
class base
{
public:
    virtual void print()
    {
        cout << "print base class" << endl;
    }
};


//Child class
class derived: public base
{
public:
    void print()
    {
        cout << "print derived class" << endl;
    }
};


int main(void)
{
    //derive class object
    derived d;
    
    //Base class pointer
    base *b = &d;
    
    // virtual function, binded at runtime
    b->print();
    
    return 0;
}

Output:

print derived class

 

Q) Write some important rules associated with virtual functions?

Below we are mentioning few rules for virtual function in C++.

  • Virtual functions cannot be static and also cannot be a friend function of another class.
  • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
  • The prototype of virtual functions should be the same in the base as well as derived class.
  • They are always defined in the base class and overridden in the derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
  • A class may have a virtual destructor but it cannot have a virtual constructor.

 

Q) Name the Operators that cannot be Overloaded.

sizeof – sizeof operator

. – Dot operator

.* – dereferencing operator

-> – member dereferencing operator

:: – scope resolution operator

?: – conditional operator

 

Q) Figure out functions that cannot be overloaded in C++?

Let see functions that can not be overloaded in C++.

1. Function declarations that differ only in the return type.

int fun()
{
    return 10;
}

char fun()
{
    return 'a';
}

 

2. Parameter declarations that differ only in a pointer * versus an array [] are equivalent.

int fun(int *ptr); 

int fun(int ptr[]);

 

3. Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent.

void fun(int ()); 

void fun(int (*)());

 

4. Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent.

int f(int x)
{
    return x;
}

int f(const int x)
{
    return x;
}

 

5. Two parameter declarations that differ only in their default arguments are equivalent.

int f ( int x, int y)
{
    return x+10;
}

int f ( int x, int y = 10)
{
    return x+y;
}

 

6. Member function declarations with the same name and the name parameter-type list cannot be overloaded if any of them is a static member function declaration.

class Test
{
    static void fun(int i) {}

    void fun(int i) {}
};

 

 

C++ Interview Questions For Experienced:

Q) Can a constructor throw an exception? How to handle the error when the constructor fails?

The constructor never throws an error.

 

Q) What is the initializer list in C++?

The initializer list is used to initialize data members of the class. The syntax of the initializer list begins with a colon(:) and then each variable along with its value separated by a comma.

Note: The initializer list does not end in a semicolon.

Let see an example to understand the initializer list  in C++,

In the below code, the member variable value is initialized by the initializer list.

#include<iostream>
using namespace std;

class Demo
{
public:
    // initialization List
    Demo(int value):value(value)
    {
        cout << "Value is " << value;
    }
private:
    int value;
};

int main()
{
    Demo obj(10);
    
    return 0;
}

Output: Value is 10

 

Q) When do we use the Initializer List in C++?

In the above question, we had seen, what is the initializer list in C++. Now let us see the situation where we have to use the Initializer List in C++.

1. In the initialization of reference members:

A reference member must be initialized using Initializer List.

#include<iostream>
using namespace std;

class Test
{
    int &m_rData;
public:
    //Initializer list must be used
    Test(int & rData):m_rData(rData) {}
    int getData()
    {
        return m_rData;
    }
};

int main()
{
    int data = 27;

    Test obj(data);

    cout<<"m_rData is " << obj.getData()<<endl;

    data = 06;

    cout<<"m_rData is " << obj.getData()<<endl;

    return 0;
}

Output:

m_rData is 27
m_rData is 6

 

2. In the initialization of non-static const data members:

const data members must be initialized using Initializer List.

#include<iostream>
using namespace std;

class Test
{
    const int m_data;
public:
    //Initializer list must be used
    Test(int x):m_data(x) {}
    int getData()
    {
        return m_data;
    }
};

int main()
{
    int data = 27;

    Test obj(data);

    cout<<"m_data is " << obj.getData()<<endl;

    return 0;
}

Output: m_data is 27

 

3. In the initialization of member objects which do not have default constructor:

See the below example, an object “a” of class “A” is a data member of class “B”, and “A” doesn’t have a default constructor. Initializer List must be used to initialize “a”.

#include <iostream>
using namespace std;

//Class A
class A
{
    int i;
public:
    A(int );
};

//Class A constructor
A::A(int arg)
{
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}


//Class B
class B
{
//obj of class A
    A a;
public:
    B(int );
};

//Class B constructor.
//Initializer list must be used for a
B::B(int x):a(x)  
{
    cout << "B's Constructor called";
}


int main()
{
    B obj(10);
    
    return 0;
}

Output:

A’s Constructor called: Value of i: 10
B’s Constructor called

 

4. In the initialization of base class members :

You have to initialize the base class members using the initialization list.

#include <iostream>
using namespace std;

//Class A
class A
{
    int i;
public:
    A(int );
};

//Class A constructor
A::A(int arg)
{
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}


//Class B
class B
{
//obj of class A
    A a;
public:
    B(int );
};

//Class B constructor.
//Initializer list to initialize base class member
B::B(int x):a(x)
{
    cout << "B's Constructor called";
}


int main()
{
    B obj(10);

    return 0;
}

Output:

A’s Constructor called: Value of i: 10
B’s Constructor called

 

5. When the constructor’s parameter name is the same as the data member:

If the constructor’s parameter name is the same as the data member name then the data member must be initialized either using this pointer or Initializer List.

#include <iostream>
using namespace std;


class Test
{
    //member name same as class constructor parameter
    int data;
public:
    Test(int data):data(data) { }
    
    int getData() const
    {
        return data;
    }
};


int main()
{
    Test obj(27);
    
    cout<<obj.getData();
    
    return 0;
}

Output: 27

 

6. To increase performance:

It is better to initialize all class variables in the Initializer List instead of assigning values inside the constructor body.

 

Q) What is a copy constructor?

A copy constructor is a member function that initializes an object using another object of the same class. If you will not create your own copy constructor then the compiler creates a default copy constructor for you.

Syntax of copy constructor:

ClassName (const ClassName &old_obj);

Example,

#include<iostream>
using namespace std;

class Foo
{
private:
    int x, y;
public:
    Foo(int x1, int y1)
    {
        x = x1;
        y = y1;
    }
    // Copy constructor
    Foo(const Foo &rOldObj)
    {
        x = rOldObj.x;
        y = rOldObj.y;
    }
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
};

int main()
{
    // Normal constructor is called here
    Foo obj1(10, 15);

    // Copy constructor is called here
    Foo obj2 = obj1;

    //Print obj1 values
    cout << "obj1.x = " << obj1.getX();
    cout << "\nobj1.y = " << obj1.getY();

    //Print obj2 values
    cout << "\n\nobj2.x = " << obj2.getX();
    cout << "\nobj2.y = " << obj2.getY();

    return 0;
}

Output:

obj1.x = 10
obj1.y = 15

obj2.x = 10
obj2.y = 15

 

Q) When are copy constructors called in C++?

There are some possible situations when copy constructor is called in C++,

  • When an object of the class is returned by value.
  • When an object of the class is passed (to a function) by value as an argument.
  • When an object is constructed based on another object of the same class.
  • When the compiler generates a temporary object.

 

Q) Why does the copy constructor take the parameter as a reference in C++?

A copy constructor is called when an object is passed by value. The copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to the copy constructor would be made to call the copy constructor which becomes a non-terminating chain of calls. Therefore, the compiler doesn’t allow parameters to be passed by value.

class Aticleworld
{
public:
   /* Incorrect: copy constructor taking parameter by value.
    *
    * It will lead to an infinite loop and ultimately a stack overflow.
    */
   Aticleworld(const Aticleworld obj)
   {

      // Copy constructor body
   }
};

 

 

Q) Why copy constructor argument should be const in C++?

There are some important reasons to use const in the copy constructor.

  • const keyword avoids accidental changes.
  • You would like to be able to create a copy of the const objects. But if you’re not passing your argument with a const qualifier, then you can’t create copies of const objects.
  • You couldn’t create copies from temporary reference, because temporary objects are rvalue, and can’t be bound to reference to non-const.

 

Q) Can one constructor of a class call another constructor of the same class to initialize this object?

Onward C++11  Yes, let see an example,

#include <iostream>
using namespace std;

class Test
{
    int a, b;
public:

    Test(int x, int y)
    {
        a= x;
        b =y;
    }
    Test(int y) : Test( 7, y) {}

    void displayXY()
    {
        cout <<"a = "<<a<<endl;
        cout <<"b = "<<b<<endl;
    }
};

int main()
{
    Test obj(27);

    obj.displayXY();

    return 0;
}

Output:

a = 7
b = 27

Note: Using some tricks you can also do in C++03. If you want to know how or know the answer then please write in the comment box.

 

Q) Can a copy constructor accept an object of the same class as a parameter, in place of reference of the object? If No, why not possible?

No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

 

Q) Are Constructors and destructors can declare as const?

Constructors and destructors can’t be declared const or volatile. They can, however, be invoked on const or volatile objects.

 

Q) Can we make a copy constructor private?

Yes, a copy constructor can be made private. When we make a copy constructor private in a class, objects of that class become non-copyable. This is particularly useful when our class has pointers or dynamically allocated resources.

 

Q) Can you explain the order of execution in the constructor initialization list?

When a class object is created using constructors, the execution order of constructors is:

  • Constructors of Virtual base classes are executed, in the order that they appear in the base list.
  • Constructors of nonvirtual base classes are executed, in the declaration order.
  • Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
  • The body of the constructor is executed.

 

Q) What is the conversion constructor?

A constructor with a single argument makes that constructor a conversion constructor and it can be used for type conversion. Let see an example code,

#include<iostream>
using namespace std;

class Demo
{
private:
    int data;
public:
    Demo(int i)
    {
        data = i;
    }
    void Display()
    {
        cout<<" data = "<<data<<endl;
    }
};


int main()
{
    Demo obj(6);

    //call display method
    obj.Display();

    // conversion constructor is called here.
    obj = 27;

    //call display method
    obj.Display();

    return 0;
}

Output:

data = 6
data = 27

 

Q) What is the difference between a copy constructor and an overloaded assignment operator?

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

#include<iostream>
using namespace std;

class Demo
{
public:
    Demo() {}
    Demo(const Demo &obj)
    {
        cout<<"Copy constructor called "<<endl;
    }
    Demo& operator = (const Demo &obj)
    {
        cout<<"Assignment operator called "<<endl;
        return *this;
    }
};

int main()
{
    Demo a, b;

    //calls assignment operator
    b = a;

    // calls copy constructor
    Demo c = a;

    return 0;
}

Output:

Assignment operator called.
Copy constructor called.

Remark:

b = a; // calls assignment operator, same as "b.operator=(a);"

Test c = a; // calls copy constructor, same as "Test c(a);"

 

Q) What is the conversion operator in C++?

A class can have a public method for specific data type conversions. It means you can define a member function of a class that converts from the type of its class to another specified type. It is called a conversion function, See the below example,

#include <iostream>
using namespace std;

class Demo
{
    double value;
public:
    Demo(double data )
    {
        value = data;
    }
    operator double()
    {
        return value;
    }
};

int main()
{
    Demo BooObject(3.4);

    /*assigning object to variable mydata of type double.
    Now conversion operator gets called to assign the value.*/

    double mydata = BooObject;

    cout << mydata <<endl;
}

Output: 3.4

 

Q) When do we need to write a user-defined destructor?

If we do not write our own destructor in class, the compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid the memory leak.

 

Q) Why a class has only one destructor?

A destructor doesn’t have parameters, so there can be only one.

 

Q) Can we have a virtual destructor in C++?

Yes, the destructor could be virtual in C++.

 

Q) When to use virtual destructors?

When we will delete an object of the derived class using a pointer to the base class that has a non-virtual destructor a results in undefined behavior.

So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to the base class. Let see an example code,

#include<iostream>
using namespace std;

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

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

int main()
{
    derived *d = new derived();

    base *b = d;

    delete b;

    return 0;
}

Output:

Constructing base
Constructing derived
Destructing derived
Destructing base

 

Q) Can we have a virtual constructor in C++?

The Constructor can’t be virtual as the constructor is a code that is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

 

Q) Can you change ‘this pointer’ of an object to point to different objects?

You can not reassign the ‘this’ pointer. This is because this pointer is rvalue when you try to point it to another object compiler gives you a warning and you will get this error “lvalue required as left operand of assignment”. The warning message could be different.

 

Q) Can you modify the ‘this pointer’ type?

“this” pointer’s type can be modified in the function declaration by the const and volatile keywords. To declare a function that has either of these attributes, add the keyword(s) after the function argument list.

See the following code,

class Point
{
    unsigned X() const;
};

int main()
{

}

The above code declares a member function, X, in which the ‘this’ pointer is treated as a const pointer to a const object. Combinations of cv-mod-list options can be used, but they always modify the object pointed to by the ‘this’ pointer, not the pointer itself.

 

Remark:The ‘this’ pointer is always a const pointer. It can’t be reassigned. The const or volatile qualifiers used in the member function declaration apply to the class instance the ‘this’ pointer points at, in the scope of that function.

 

Q) Can I use realloc() on pointers allocated via new?

NO.

 

Q) Why should C++ programmers minimize the use of ‘new’?

In dynamic memory allocation, bookkeeping is more complex and allocation is slower. Also, one biggest problem is that there is no implicit release point, you must release the allocated memory manually, using the delete or delete[].

 

Q) Can I free() pointers allocated with new?

No. Very dangerous, never do such type mistake.

 

Q #) Is there any problem with the following : char*a=NULL, char& p = *a?

The result is undefined. You should never do this. A reference must always refer to some valid object.

 

Q) Can I delete pointers allocated with malloc()?

No. It gives you undefined results.

 

Q) How to call a non-const member function from a const member function in C++?

Let see an example code to understand these questions, when you will call the increment in display function you will get the error because you are breaking the rule.

#include<iostream>
using namespace std;

class Demo
{
    int m_value;
public:
    Demo()
    {
        m_value = 0;
    }
    int incrementValue();
    //const member function
    void display() const;
};

int Demo::incrementValue()
{
    return (++m_value);
}

void Demo::display() const
{
    int value = incrementValue();
    cout<< value <<endl;
}

int main()
{
    class Demo obj;

    obj.display();

    return 0;
}

Output:

Compilation error

So to avoid this you need to do some tricks, Now see the code.

#include<iostream>
using namespace std;

class Demo
{
    int m_value;
public:
    Demo()
    {
        m_value = 0;
    }
    int incrementValue();
    void display() const;
};

int Demo::incrementValue()
{
    return (++m_value);
}

void Demo::display() const
{
    int value = (const_cast<Demo*>(this))->incrementValue();
    cout<< value <<endl;
}

int main()
{
    class Demo obj;

    obj.display();

    return 0;
}

Code will compile successfully.

 

Remark: Never try to break your promise might get undefined behavior.

 

Q) How to create .dll in C++ and how to link .dll in your code?

You can see this Link for the answer: How to create and use DLL.

 

Q) When should I use references, and when should I use pointers?

In a single statement, “use references when you can, and pointers when you have to”. References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside.

The exception to the above is where a function’s parameter or return value needs a “sentinel” reference a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references should always alias objects, not a dereferenced NULL pointer).

 

Q) What are VTABLE and VPTR?

Remark: vptr and vtbl are Implementations defined the C++ standard does not even talk about them.

Vtable: The virtual table is a lookup table of functions used to resolve function calls in a dynamic/late binding manner. The compiler builds this vTable at compile time. The virtual table sometimes goes by other names, such as “vtable”, “virtual function table”, “virtual method table”, or “dispatch table”.

vptr:When you create an object of a class that contains the virtual function, then the compiler added a pointer to this object as a hidden member. This hidden pointer is called virtual table pointer, vpointer, or VPTR. This vptr stores the address of the vtable.

 

Q) How virtual functions are implemented in C++?

Virtual functions are implemented using a table of function pointers, called the VTABLE. There is one entry in the table per virtual function in the class. This table stores the address of the virtual function and it is created by the constructor of the class.

The object of the class containing the virtual function contains a virtual pointer (vptr) that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve the function address.

Due to the vptr, the size of the object increases by the size of the pointer. The vptr contains the base address of the virtual table in memory. Note that virtual tables are class-specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains.

At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.

Note: You should not call the virtual function in the constructor. Because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions.

 

Q) Is there a separate vtable for each object?

No, there will be 1 vtable per class, not per object.

 

Q) Can virtual functions be inlined?

Whenever a virtual function is called using a base class reference or pointer it cannot be inlined (because the call is resolved at runtime), but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.

 

Q) Can a virtual function is called inside a non-virtual function in C++?

Yes. We can call.

 

Q) What is a pure virtual function in C++?

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.  We can not instantiate the abstract class and we have to define it in the derived class.

Let see the below example.

#include<iostream>
using namespace std;

class Base
{
public:
    //pure virtual function
    virtual void fun() = 0;
};

class Child: public Base
{
public:
    void fun()
    {
        cout << "Child class fun is called";
    }
};

int main()
{
    Child d;

    d.fun();

    return 0;
}

Output: Child class fun is called

 

Q) What is difference between Virtual function and Pure virtual function in C++?

There are some differences between a virtual function and a pure virtual function that I have arranged in a table for easier comparison:

VIRTUAL FUNCTION PURE VIRTUAL FUNCTION
Syntax: virtual int fun(); Syntax:  virtual int fun() = 0;
A virtual function is a member function of the base class which can be redefined by the derived class. A pure virtual function is a member function of the base class whose only declaration is provided in the base class and must be defined in the derived class.
Classes having virtual functions are not abstract. The base class containing pure virtual function becomes abstract.
The definition is given in base class. No definition is given in base class.
The base class having virtual function can be instantiated i.e. its object can be made. The base class having pure virtual function becomes abstract i.e. it cannot be instantiated.
If a derived class does not redefine the virtual function of the base class, then it does not affect compilation. If a derived class does not redefine the virtual function of the base class, then compilation error occurs.
All derived class may or may not redefine the virtual function of base class. All derived classes must redefine the pure virtual function of the base class.

Note: Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;

 

Q) Why is a pure virtual function initialized by 0?

The reason =0 is used is that Bjarne Stroustrup didn’t think he could get another keyword, such as “pure” past the C++ community at the time the feature was being implemented. This is described in his book, The Design & Evolution of C++, section 13.2.3:

 

Q) Can we access private data members of a class without using a member or a friend function?

You can’t. That member is private, it’s not visible outside the class. That’s the whole point of the public/protected/private modifiers.

Note: You could probably use dirty pointer tricks though, but my guess is that you’d enter undefined behavior territory pretty fast.

 

Q) Can virtual functions be private in C++?

Yes, the virtual function can be private. Let see an example code,

#include<iostream>
using namespace std;

class Base
{
public:
    void test();
private:
    //private virtual function
    virtual void fun()
    {
        cout << "Base Function"<<endl;
    }
};


class Derived: public Base
{
public:
    void fun()
    {
        cout << "Derived Function"<<endl;
    }
};
void Base::test()
{
    Derived objDerived;
    Base *ptr = &objDerived;
    ptr->fun();
}


int main()
{
    Base Obj;
    
    Obj.test();
    
    return 0;
}

Output:

Derived Function

 

Q) What is an abstract class?

An abstract class is a class for which one or more functions are declared but not defined (have one or more functions pure virtual), meaning that the compiler knows these functions are part of the class, but not what code to execute for that function. These are called abstract functions. Here is an example of an abstract class.

class shape
{
public:
    virtual void Calculate() = 0;
};

Note: We can not be instantiated, abstract class.

 

Q) Write down some important points related to abstract function?

There are some important points related to the abstract function.

  • A class is abstract if it has at least one pure virtual function.
  • We can create pointers and references to abstract class type.
  • If we do not override the pure virtual function in the derived class, then derived class also becomes an abstract class.
  • An abstract class can have constructors.

 

Q) What is the difference between a concrete class and an abstract class?

Abstract class:

An abstract class is a class for which one or more functions are declared but not defined (have one or more functions pure virtual), meaning that the compiler knows these functions are part of the class, but not what code to execute for that function. These are called abstract functions. Here is an example of an abstract class.

class shape
{
public:
    virtual void Calculate() = 0;
};

Concrete class:

A concrete class is an ordinary class that has no pure virtual functions and hence can be instantiated.

class message
{
public:
    void Display()
    {
        cout <<"Hello";
    }
};

 

Q) How to access derived class function from the base class object without using virtual function?

Using the typecasting we can call derive class object but not recommended because you have a virtual keyword. Let see an example program for the same,

#include<iostream>
using namespace std;


class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};

class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};

int main()
{
    B bObj;

    A *aObj = &bObj;

    aObj->fun();

    return 0;
}

Output:

Base Class fun.

Now access derived class member using the typecasting but is not recommended,

#include<iostream>
using namespace std;

//Base class
class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};

//Child class
class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};
int main()
{
    B bObj;
    A *aObj = &bObj;
    
    //Now Access child class but not recommended
    static_cast<B*>(aObj)->fun();
    
    return 0;
}

Output:

Child Class fun.

 

Q) What is a template function?

Using the template we can create a generic function that will perform the set of operations on different data types. The type of data that the function will operate upon is passed to it as a parameter. Let see an example code,

In the below code, I am creating a generic function using the template that will find the smallest number among two passed numbers.

#include <iostream>
using namespace std;

template <typename T>
T findMinNumber(T x, T y)
{
    return (x < y)? x: y;
}

int main()
{
    cout << findMinNumber<int>(2, 7) << endl; // Call findMinNumber for int
    cout << findMinNumber<double>(3.5, 7.0) << endl; // call findMinNumber for double
    cout << findMinNumber<char>('d', 'p') << endl; // call findMinNumber for char
    
    return 0;
}

Output:

2
3.5
d

 

Q) What is the difference between function overloading and templates?

Both function overloading and templates are examples of polymorphism features of OOP. Function overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations.

 

Q) Can we combine C and C++ code?

Yes, we can combine C and C++ source code. You need to use extern “C”  for the same. Let see an example,

// C++ code
 extern "C" void foo(int); // one way, foo is C function


 extern "C" {    // another way, fun and test are C functions
     int fun(double);
     double test();
 };

 

Q) How can I include a non-system C header file in my C++ code?

If you are including a C header file that isn’t provided by the system, you may need to wrap the #include line in an extern “C” { /*…*/ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.

// This is C++ code
extern "C" {
    // Get declaration for f(int i, char c, float x)
#include "my-C-code.h"
}

int main()
{
    f(7, 'x', 3.14);   // Note: nothing unusual in the call
    // ...
}

 

Q) What is the effect of extern “C” in C++?

extern “C” makes a function-name in C++ have ‘C’ linkage (the compiler does not mangle the name) so that client C code can link to (i.e use) your function using a ‘C’ compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client ‘C’ linker will then link to using the ‘C’ name.

 

Q) Why do C++ compilers need name mangling?

Name mangling is the rule according to which C++ changes function’s name into function signature before passing that function to a linker. This is how the linker differentiates between different functions with the same name.

 

Q) What is typecasting?

Converting an expression of a given type into another type is known as type-casting.

 

Q) When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used?

dynamic_cast:  It is used for converting pointers/references within an inheritance hierarchy.

static_cast: It is used for ordinary type conversions.

reinterpret_cast: reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked..Use with extreme caution.

const_cast: It is used for casting away const/volatile. Avoid this unless you are stuck using a const-incorrect API.

 

Q) How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

Preprocessing:  The preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a “pure” C++ file without pre-processor directives.

Compilation: The compiler takes the preprocessor’s output and produces an object file from it.

Linking: The linker takes the object files produced by the compiler and produces either a library or an executable file.

 

Q) How to make a C++ class whose objects can only be dynamically allocated?

Create a private destructor in the class. When you make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because the compiler needs to remove them from the stack segment once they are not in use.

 

Q) What does the explicit keyword mean?

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions.

 

Q) How do you access the static member of a class?

We can access static members in two ways, using the class name with help of resolution operator and with the class object.

 

Q) Distinguish between shallow copy and deep copy?

Comparison chart explains the difference between the Shallow Copy and Deep Copy:

Shallow Copy Deep Copy
Shallow Copy stores the references of objects to the original memory address. Deep copy stores copies of the object’s value.
Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn’t reflect changes made to the new/copied object in the original object.
Shallow copy is faster. Deep copy is comparatively slower.

 

Q) Friend class and function in C++?

Friend Class:

A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private members of another class.

Friend Function:

A friend’s function can be given a special grant to access private and protected members. A friend function can be:
a) A method of another class
b) A global function

 

Q) What is the Diamond problem? How can we get around it?

C++ allows multiple inheritances. Multiple inheritances allow a child class to inherit from more than one parent class. The diamond problem occurs when two superclasses of a class have a common base class. For example, in the following diagram, the “D class” gets two copies of all attributes of “A class”, which causes ambiguities. Let see the below image which shows what happens without virtual inheritance?

A   A  
|   |
B   C  
 \ /  
  D

The solution to this problem is the ‘virtual’ keyword. We make the classes “B” and “C” as virtual base classes to avoid two copies of class “A” in the “D” class.

  A  
 / \  
B   C  
 \ /  
  D

 

Q) Why virtual functions cannot be static in C++?

Virtual functions are invoked when you have a pointer/reference to an instance of a class. Static functions aren’t tied to a particular instance, they’re tied to a class

 

Q) Count the number of words, characters, and lines in a file?

See this Article, Count number of words.

 

Q) What is the “mutable” keyword in C++?

This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

Let see the below code, where I am incrementing the mutable variable in a const member function. If you will remove the mutable keyword you will get a compiler error.

#include <iostream>
using namespace std;

class Demo
{
public:
    Demo():m_accessCount(0)
    {
    }
    int GetData() const
    {
        return (++m_accessCount);
    }
private:
    mutable int m_accessCount;
};

int main()
{
    Demo obj;
    cout << obj.GetData()<<endl;
    return 0;
}

Output: 1

 

Q) How to handle the exception in C++?

An exception is a problem that arises during the execution of a program. One of the advantages of C++ over C is Exception Handling.

C++ provides the following specialized keywords to handle the exception,

try:  A try represents a block of code that can throw an exception.

catch: A catch represents a block of code that is executed when a particular exception is thrown.

throw:The throw keyword is used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.

 

Q) What is a Memory Leak?

memory leak is a common and dangerous problem. It is a type of resource leak. In C language, a memory leak occurs when you allocate a block of memory using the memory management function and forget to release it.

int main ()
{
    char * pBuffer = malloc(sizeof(char) * 20);
    /* Do some work */
    return 0; /*Not freeing the allocated memory*/
}

Note: Once you allocate a memory than allocated memory does not allocate to another program or process until it gets free.

For more detail see this article, Problem with dynamic memory allocation

 

Q) Why static functions cannot access non-static variables?

Because a static function by definition is not tied to any single object of the class, while non-static variables always refer to an actual object in some way.

 

Q) What is a dangling pointer?

Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. It creates a problem because the pointer is still pointing the memory that is not available. When the user tries to dereference the daggling pointers then it shows the undefined behavior and can be the cause of the segmentation fault.

 

 

Q) What is the difference between a macro and a function?

macro VS function

For more details, you can see the below-mentioned articles,

 

Q) STL Containers – What are the types of STL containers?

A Standard Template Library (STL) is a library of container templates approved by the ANSI committee for inclusion in the standard C++ specification. We have various types of STL containers depending on how they store the elements.

Queue, Stack: These are the same as traditional queue and stack and are called adaptive containers.
Set, Map: These are basically containers that have key/value pairs and are associative in nature.
Vector, deque: These are sequential in nature and have similarities to arrays.

 

Q) What is the return value of malloc (0)?

If the size of the requested space is zero, the behavior will be implementation-defined. The return value of the malloc could be a null pointer or it shows the behavior of that size is some nonzero value. It is suggested by the standard to not use the pointer to access an object that is returned by the malloc while the size is zero.

 

Q) What are the post-increment and decrement operators?

When we use a post-increment (++) operator on an operand then the result is the value of the operand and after getting the result, the value of the operand is incremented by 1. The working of the post-decrement (–) operator is similar to the post-increment operator but the difference is that the value of the operand is decremented by 1.

Note: incrementation and decrementation by 1 are the types specified.

 

Q) Are the expressions *ptr++ and ++*ptr same?

Both expressions are different. Let’s see a sample code to understand the difference between both expressions.

#include <stdio.h>

int main(void)
{
    int aiData[5] = {100,200,30,40,50};

    int *ptr = aiData;

    *ptr++;

    printf("aiData[0] = %d, aiData[1] = %d, *piData = %d", aiData[0], aiData[1], *ptr);

    return 0;
}

Output: 100, 200, 200

Explanation:

In the above example, two operators are involved and both have different precedence. The precedence of post ++ is higher than the *, so first post ++ will be executed and above expression, *p++ will be equivalent to *(p++). In another word you can say that it is post-increment of address and output is 100, 200, 200

 

#include <stdio.h>

int main(void)
{
    int aiData[5] = {100,200,300,400,500};
    
    int *ptr = aiData;

    ++*ptr;

    printf("aiData[0] = %d, aiData[1] = %d, *ptr = %d", aiData[0], aiData[1], *ptr);

    return 0;
}

Output: 101 , 200 , 101

Explanation:

In the above example, two operators are involved and both have the same precedence with a right to left associativity. So the above expression ++*p is equivalent to ++ (*p). In another word, we can say it is a pre-increment of value and output is 101, 200, 101.

 

Q) What is the difference between global and static global variables?

Global and static global variables have different linkages. It is the reason global variables can be accessed outside of the file but the static global variable only accesses within the file in which it is declared.

A static global variable            ===>>>  internal linkage.
A non-static global variable  ===>>>  external linkage.

 

Q) What is the difference between const and macro?

  • The const keyword is handled by the compiler, in another hand, a macro is handled by the preprocessor directive.
  • const is a qualifier that is modified the behavior of the identifier but macro is preprocessor directive.
  • There is type checking is occurred with a const keyword but does not occur with #define.
  • const is scoped by C block, #define applies to a file.
  • const can be passed as a parameter (as a pointer) to the function. In the case of call by reference, it prevents to modify the passed object value.

 

Q) What are the functions of the scope resolution operator?

The functions of the scope resolution operator include the following.

  • It helps in resolving the scope of various global variables.
  • It helps in associating the function with the class when it is defined outside the class.

See the below code in which using the resolution operator we are accessing the global variable,

#include <iostream>
using namespace std;
int data = 0;

int main()
{
    int data = 0;

    ::data = 1;  // set global data to 1

    data = 2;    // set local data to 2

    cout << ::data << ", " << data;

    return 0;
}

Output: 1, 2

 

Q) Write a program that describes the safe way to access one object to another in C++?

Let see an example, where class  A object is calling from class B. In the first example, I am calling class a function in the constructor of class B.

#include<iostream>
using namespace std;

class A
{
public:
    A()
    {
        cout << "class  A constructor" <<endl;
    }
    void f()
    {
        cout << "class  A function" <<endl;
    }
};


class B
{
public:
    B(class A *a)
    {
        cout << "class  B constructor" <<endl;
        a->f();
    }
};

extern class A a;
class B b(&a);
class A a;

int main()
{
    return 0;
}

Output:

class B constructor
class A function
class A constructor

You can see when we are running the code class A function is calling before the calling of the constructor of class A. It is unsafe and might show undefined behavior.

So below we are modifying the code for safety. In the below code function only call after the construction of class A.

#include<iostream>
using namespace std;

class A
{
public:
    A()
    {
        cout << "class  A constructor" <<endl;
    }
    void f()
    {
        cout << "class  A function" <<endl;
    }
};

class B
{
public:
    B(class A *a)
        : pFun(a)
    {
        cout << "class  B constructor" <<endl;
    }
    void init()
    {
        pFun->f();
    }
    class A *pFun;
};

extern class A a;
class B b(&a);
class A a;

int main()
{
    //Now Safe to access one object from another
    b.init();
    
    return 0;
}

Output:

class B constructor
class A constructor
class A function

 

Q) Could you write an example code that describes the use of explicit keyword?

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. So it is a good practice to add explicit keywords with constructors. Let see example codes to understand this concept.

#include<iostream>
using namespace std;

class Demo
{
private:
    int data;
public:
    Demo(int i):data(i)
    {
    }
    void Display()
    {
        cout<<" data = "<<data<<endl;
    }
};

int main()
{
    Demo obj(6);

    obj.Display();

    obj = 27; // implicit conversion occurs here.

    obj.Display();

    return 0;
}

In the above-mentioned code, you can see how the constructor is working as a conversion constructor when assigning 27 to the object. When you will compile this code then it would be compiled and display the value of data.

I think you want to avoid this accidental construction because it can hide a bug. So using the explicit keyword we can avoid it. Because we know that prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Let see a code to understand this concept.

#include<iostream>

using namespace std;

class Demo
{
private:
    int data;
public:
    explicit Demo(int i):data(i)
    {
    }
    void Display()
    {
        cout<<" data = "<<data<<endl;
    }
};

int main()
{
    Demo obj(6);

    obj.Display();

    obj = 27; // implicit conversion occurs here.

    obj.Display();

    return 0;
}

Output:

explicit keyword c++

 

Q) Why is “using namespace std;” considered bad practice?

We should always avoid including namespace and call the function followed by the namespace name. Let’s assume you want to display something on console then you should write the code in the below format,

std::cout << "Aticleworld.com";

The reason behind that it helps to avoid ambiguity when two included namespaces have the function of the same name.

 

Q) Why can templates only be implemented in the header file?

It is not necessary to implement or define a template in the header file but we can define in .cpp. But if you are defining the methods in .cpp file then you have to include .cpp file in template header file either you need to define the template type explicitly in .cpp file. Let me know if you want a detailed article on this topic.

 

Q) Do all virtual functions need to be implemented in derived classes?

The derived classes do not have to implement all virtual functions themselves. See the below example code,

#include<iostream>
using namespace std;

//Base class
class base
{
public:
    virtual void print()
    {
        cout << "print base class" << endl;
    }
    virtual void display()
    {
        cout << "print base class" << endl;
    }
};


//Child class
class derived: public base
{
public:
    void print()
    {
        cout << "print derived class" << endl;
    }
};

int main()
{
    //derive class object
    derived d;

    //Base class pointer
    base *b = &d;

    // virtual function, binded at runtime
    b->print();

    return 0;
}

Output:

print derived class

 

Q) Do all pure virtual functions need to be implemented in derived classes?

We have to implement all pure virtual functions in derived class only if the derived class is going to be instantiated. But if the derived class becomes a base class of another derived class and only exists as a base class of more derived classes, then derived class responsibility to implement all their pure virtual functions.

The “middle” class in the hierarchy is allowed to leave the implementation of some pure virtual functions, just like the base class. If the “middle” class does implement a pure virtual function, then its descendants will inherit that implementation, so they don’t have to re-implement it themselves. Let see an example code to understand the concept.

#include<iostream>
using namespace std;

class ISuperbase
{
public:
    //pure virtual functions
    virtual void print() = 0;
    virtual void display() = 0;
};

//derived from Interface
class Base: public ISuperbase
{
public:
    virtual void print()
    {
        cout << "print function of middle class" << endl;
    }
};


//derived from Base
class Derived :public Base
{
    virtual void display()
    {
        cout << "In display function" << endl;
    }
};

int main()
{
    //derive class object
    Derived d;
    
    // virtual function, binded at runtime
    d.print();
    
    return 0;
}

Output:

print function of middle class

 

Q) How to call a parent class function from a derived class function?

If a function is defined in a base class and it is not private then it is available in the derived class. You can call it in the derived class using the resolution operator (::). Let see a code where I am accessing the parent class function in the derived class as well as from the derived class object.

#include<iostream>
using namespace std;


class Base
{
public:
    virtual void print()
    {
        cout << "I am from base class" << endl;
    }
};


class Derived :public Base
{
    void display()
    {
        //calling base class function
        Base::print();
    }
};


int main()
{
    //derive class object
    Derived d;
    
    //calling print function
    d.print();
    
    //Calling print function of parent class
    // using derived class object
    d.Base::print();
    
    return 0;
}

Output:

I am from base class

I am from base class

 

Q) How to access members of the namespace in different files?

With help of an extern keyword, we can do this, see the below example code.

//common.h
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED

namespace ATIC
{
  extern int data;
}

#endif // COMMON_H_INCLUDED

 

//test.cpp
#include "common.h"

namespace ATIC
{
  int data = 27;
}

 

//main.cpp
#include <iostream>
#include "common.h"

int main()
{
    std::cout << ATIC::data << std::endl;

    return 0;
}

 

Q) How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function, then you can use the below expression.

//Example

std::string str;

const char * c = str.c_str();

 

If you want to get a writable copy, like char *, you can do that with this:

std::string str;

char * writable = new char[str.size() + 1];

std::copy(str.begin(), str.end(), writable);

writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

NoteThe above code is not exception-safe.

We can also do it with std::vector, it completely manages the memory for you.

std::string str;

std::vector<char> writable(str.begin(), str.end());

writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

 

Q) What is the exact output of the program below?

#include <iostream>
using namespace std;


int main()
{
    int x = 4, y = 2;

    cout << ++x << endl;
    cout << x << endl;
    cout << x++ << endl;
    cout << x << endl;
    cout << -x << endl;
    cout << x << endl;
    cout << --x << endl;
    cout << x << endl;
    cout << x-- << endl;
    cout << x << endl;
    cout << x + y << endl;
    cout << x << endl;
    cout << y << endl;
    cout << x << y << endl;
    cout << x << endl;
    cout <<"x * x = ";
    cout << x * x << endl;
    cout << 'x' << endl;

    return 0;
}

 

Some MCQs Related to C++ interview Questions:

C++ MCQ

C++ OOPS Multiple Choice Questions And Answers

1 / 60

When a virtual function is redefined by the derived class, it is called___________.

2 / 60

How compile-time polymorphisms are implemented in C++?

3 / 60

How can we make a C++ class such that objects of it can only be created using new operator? If the user tries to create an object directly, the program produces compiler error.

4 / 60

What does polymorphism in OOPs mean?

5 / 60

While redefining a virtual function in the derived class, if its prototype is changed then ___________________ .

6 / 60

Which of the following is not a type of Constructor?

7 / 60

Assigning one or more function body to the same name is called ____________ .

8 / 60

Constant variables can be created in CPP by using ________ .

9 / 60

The member in a class by default is ____?

10 / 60

How structures and classes in C++ differ?

11 / 60

Wrapping data and its related functionality into a single entity is known as _____________

12 / 60

What is the effect of a negative number in a field width specifier?

13 / 60

const member function does not allow to modify/alter the value of any data member of the class.

14 / 60

Which of the following explains Polymorphism?

1.

int func(int, int);
float func1(float, float);

2.

int func(int);
int func(int);

3.

int func(float);
float func(int, int, char);

4.

int func();
int new_func();

 

 

15 / 60

What does modularity mean?

16 / 60

Which of the following is true about inline functions and macros.

17 / 60

Pick the correct statement about references.

18 / 60

Which of the following is not correct for virtual function in C++?

19 / 60

_________________are used for generic programming.

20 / 60

Which one of the following is not a member of the class?

21 / 60

What is the syntax of class template?

22 / 60

Which of the following approach is followed by the c++

23 / 60

Method overriding can be prevented by using the final as a modifier at ______.

24 / 60

Can constructors be overloaded?

25 / 60

Which OOPs concept is allowed to reuse the code?

26 / 60

In any ways, Non-member function cannot have access to the private data of the class.

27 / 60

The associativity of which of the following operators is Left to Right, in C++?

28 / 60

Which of the following is not correct (in C++) ?

1. Class templates and function templates are instantiated in the same way.
2. Class templates differ from function templates in the way they are initiated.
3. Class template is initiated by defining an object using the template argument.
4. Class templates are generally used for storage classes.

29 / 60

In CPP, cin and cout are the predefined stream __________ .

30 / 60

How many types of polymorphism in c++?

31 / 60

Assume class TEST. Which of the following statements is/are responsible to invoke copy constructor?

32 / 60

In CPP program, Can we declare and define a user defined function inside a struct as we do in a class ?

33 / 60

Which symbol is used as an address operator?

34 / 60

How access specifiers in Class helps in Abstraction?

35 / 60

A member function can always access the data in __________ , (in C++).

36 / 60

Which of the following is an abstract data type?

37 / 60

Which of the following class allows to declare only one object of it?

38 / 60

Which of the not an inheritance?

39 / 60

Which of the following is correct?

40 / 60

If base class has constructor with arguments, then it is ________________ for the derived class to have constructor and pass the arguments to base class constructor.

41 / 60

Which of the following are true about Virtual functions?

42 / 60

In C++, polymorphism requires:

43 / 60

Why references are different from pointers?

44 / 60

How the template class is different from the normal class?

45 / 60

While overloading binary operators using member function, it requires ___ argument/s.

46 / 60

What is the difference between references and pointers?

47 / 60

An operator function is created using _____________ keyword.

48 / 60

A virtual function that has no definition within the base class is called____________.

49 / 60

Which of the following function must use reference.

50 / 60

If a class contains static variable, then every object of the class has its copy of static variable.

51 / 60

Which operator is overloaded for cout operation?

52 / 60

How run-time polymorphisms are implemented in C++?

53 / 60

Which of the following provides a programmer with the facility of using the object of a class inside other classes?

54 / 60

Which of the following shows multiple inheritances?

55 / 60

Identify the incorrect statement.

56 / 60

What are the things that are inherited from the base class?

57 / 60

If abstract class is inherited by derived class, then_______________ .

58 / 60

Inline functions are useful when

59 / 60

Classes in CPP are________

60 / 60

Who is the father of C++?

 

Some unsolved Questions for you:

Q) How are .h files loaded and linked with their .c files?

Q) Which is faster: Stack allocation or Heap allocation?

Q) What is an auto pointer in C++?

Q) What is the smart pointer in C++?

Q) What is the difference between an array and a list?

Q) What is a shared pointer in c++?

Q) What are the debugging methods you use when you came across a problem?

Q) How do I convert an integer to a string in C++?

Q) Any fundamental difference between source and header files in C?

 

 

Recommended Articles for you: