HtmlCssMonk

60 Most important C++ Interview Questions and Answers

By – HtmlCssMonk

60 Most Frequently asked basic and advanced C++ Interview Questions with code examples for entry-level candidates as well as experienced professionals.

C++ is still as relevant today as it was during its advent in the mid-80s. The imperative, object-oriented programming language is widely used as a general-purpose programming language. As such, several jobs require candidates to have a profound understanding of C++.

Following is a list of C++ interview questions and answers, which are likely to be asked during the interview.

Also Try-Test your Skills with Amazing Quizzes.

Let’s get started.

1- What is C++?

C++ is a computer programming language that is a superset of C wherein additional features are made in the C language. 

2- Define Class in C++?

The class generally specifies the structure of data. It can be defined as the blueprint that describes the states of supported types. For e.g. the details of the student in student class like student’s age, name, address, etc. in one block that is class.

3- Define Object in C++?

Object is an instance of the class. An object can have fields, methods, constructors, and related. For example, a bike in real life is an object, but it has various features such as brakes, color, size, design, and others, which are instances of its class.

4- What are the advantages of C++?

C++ doesn’t only maintains all aspects from C language, it also simplifies memory management and adds several features like:

  • C++ is a highly portable language means that the software developed using C++ language can run on any platform.
  • C++ is an object-oriented programming language which includes the concepts such as classes, objects, inheritance, polymorphism, abstraction.
  • C++ has the concept of inheritance. Through inheritance, one can eliminate the redundant code and can reuse the existing classes.
  • Data hiding helps the programmer to build secure programs so that the program cannot be attacked by the invaders.
  • Message passing is a technique used for communication between the objects.
  • C++ contains a rich function library.

5- What is the difference between C and C++?

Following are the differences between C and C++:

CC++
C language was developed by Dennis Ritchie.C++ language was developed by Bjarne Stroustrup.
C is a structured programming language.C++ supports both structural and object-oriented programming language.
C is a subset of C++.C++ is a superset of C.
In C language, data and functions are the free entities.In the C++ language, both data and functions are encapsulated together in the form of a project.
C does not support the data hiding. Therefore, the data can be used by the outside world.C++ supports data hiding. Therefore, the data cannot be accessed by the outside world.
C supports neither function nor operator overloading.C++ supports both function and operator overloading.
In C, the function cannot be implemented inside the structures.In the C++, the function can be implemented inside the structures.
Reference variables are not supported in C language.C++ supports the reference variables.
C language does not support the virtual and friend functions.C++ supports both virtual and friend functions.
In C, scanf() and printf() are mainly used for input/output.C++ mainly uses stream cin and cout to perform input and output operations.

6- Explain the features or concepts of Object-oriented programming (OOP)?

The features or concepts of OOP are as below:

  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism

Abstraction: It is used for hiding the internal implementations and displays only the required details to the user. Abstraction can be implemented with the help of abstract class or interface. For e.g. Calculator. In the calculator, it shows only output whatever input is given. How the calculations are done, that is not necessary detail for the user.

Encapsulation: It is referred to as data hiding. It is a mechanism that binds the data and operations together and hides that details from the user. Encapsulation can be achieved with the help of access specifiers that are public, private and protected in C++. With the help of them, we can provide access or prevent the access directly to a user.

Inheritance: It is referred to as a process of creating new classes from existing classes. It means to inherit the properties of the parent class by the child class. The parent class is also called as Base class and child class is also referred to as a Derived class. Inheritance is used mainly for code reusability and to extend the parent classes.

Polymorphism: It refers to many forms. It mainly describes as when a member function is called, it will execute the different function depending on the type of object that to invoke the function.

7- What are the access specifiers in C++?

In an object-oriented language, access specifiers are referred to as the keywords that are used to set the accessibility of classes, function, methods and other members. There are only 3 access specifiers for C++ that are: 1. Public 2. Private 3. Protected

  • Public: The members or fields that are declared as public can be accessed outside the class as well.
  • Private: The members or fields that are declared as private cannot be accessed outside the class. They can be accessed only inside the class.
  • Protected: The members or fields that are declared as protected can be accessed outside the class but only in a class derived from that class.

8- Briefly explain the concept of Inheritance in C++.

C++ allows classes to inherit some of the commonly used state and behavior from other classes. This process is known as inheritance.

9- Define a namespace?

A namespace is used for resolving the name conflict of the identifier, which is accomplished by placing them under various namespaces. This way, it helps in the logical division of the different codes.

10- What are the Comments in C++?

Comments in C++ are simply a piece of source code ignored by the compiler. They are only helpful for a programmer to add a description or additional information about their source code.

In C++ there are two ways to add comments:

  • //single-line comment
  • /* block comment */

The first type will discard everything after the compiler encounters “//”. In the second type, the compiler discards everything between “/*” and “*/”.

11- Difference between Declaration and Definition of a variable.

The declaration of a variable is merely specifying the data type of a variable and the variable name. As a result of the declaration, we tell the compiler to reserve the space for a variable in the memory according to the data type specified.

Example:

int Result;char c;int a,b,c;

All the above are valid declarations. Also, note that as a result of the declaration, the value of the variable is undetermined.

Whereas, a definition is an implementation/instantiation of the declared variable where we tie up appropriate value to the declared variable so that the linker will be able to link references to the appropriate entities.

From above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

12- Comment on Local and Global scope of a variable.

The scope of a variable is defined as the extent of the program code within which the variable remains active i.e. it can be declared, defined or worked with.

There are two types of scope in C++:

  1. Local Scope: A variable is said to have a local scope or is local when it is declared inside a code block. The variable remains active only inside the block and is not accessible outside the code block.
  2. Global Scope: A variable has a global scope when it is accessible throughout the program. A global variable is declared on top of the program before all the function definitions.

Example:

include 
 Int globalResult=0; //global variable
 int main()
 {
 Int localVar = 10; //local variable.
 ….. 
 }

13- What is the difference between reference and pointer?

Following are the differences between reference and pointer:

ReferencePointer
Reference behaves like an alias for an existing variable, i.e., it is a temporary variable.The pointer is a variable which stores the address of a variable.
Reference variable does not require any indirection operator to access the value. A reference variable can be used directly to access the value.Pointer variable requires an indirection operator to access the value of a variable.
Once the reference variable is assigned, then it cannot be reassigned with different address values.The pointer variable is an independent variable means that it can be reassigned to point to different objects.
A null value cannot be assigned to the reference variable.A null value can be assigned to the reference variable.
It is necessary to initialize the variable at the time of declaration.It is not necessary to initialize the variable at the time of declaration.

14- What are the different types of polymorphism in C++?

Polymorphism: Polymorphism means multiple forms. It means having more than one function with the same function name but with different functionalities.

Polymorphism is of two types:

  • Runtime polymorphism

Runtime polymorphism is also known as dynamic polymorphism. Function overriding is an example of runtime polymorphism. Function overriding means when the child class contains the method which is already present in the parent class. Hence, the child class overrides the method of the parent class. In case of function overriding, parent and child class both contains the same function with the different definition. The call to the function is determined at runtime is known as runtime polymorphism.

  • Compile time polymorphism

Compile-time polymorphism is also known as static polymorphism. The polymorphism which is implemented at the compile time is known as compile-time polymorphism. Method overloading is an example of compile-time polymorphism.

Method overloading: Method overloading is a technique which allows you to have more than one function with the same function name but with different functionality.

Method overloading can be possible on the following basis:

  • The return type of the overloaded function.
  • The type of the parameters passed to the function.
  • The number of parameters passed to the function.

15- What are the types of inheritance in C++?

There are different types of Inheritance in C++ :

  • Single Inheritance: It refers to the inheritance when there is only one parent class and child class.
  • Multiple Inheritance: It refers to inheritance when a derived class inherits the properties of two or more classes.
  • Multilevel Inheritance: It refers to inheritance when the derived class is base class for another class.
  • Hierarchical Inheritance: It refers to inheritance when multiple derived classes inherit the properties of the same base class.
  • Hybrid Inheritance: It refers to Virtual Inheritance. It is a combination of Multilevel and Hierarchical inheritance.

16- What are the data types and variables in C++?

Data types are used to define the type of variable and accordingly, OS allocates the memory space and what can be stored.

Variables are declared for which the value will be assigned and while declaring it reserves the memory space to hold the values.

For e.g. int X, in this example, ‘int’ is data type and ‘X’ is variable. Some data type examples are int, char, float, long, bool, double, void.

17- What is the function of the keyword “Volatile”?

“Volatile” is a function that helps in declaring that the particular variable is volatile and thereby directs the compiler to change the variable externally- this way, the compiler optimization on the variable reference can be avoided.

18- Define storage class in C++? Name some?

Storage class in C++ specifically resemble life or even the scope of symbols, including the variables, functions, etc. Some of the storage class names in C++ include mutable, auto, static, extern, register, etc.

19- Can we have a recursive inline function in C++?

Even though it is possible to call an inline function from within itself in C++, the compiler may not generate the inline code. This is so because the compiler won’t determine the depth of the recursion at the compile time.

Nonetheless, a compiler with a good optimizer is able to inline recursive calls until some depth is fixed at compile-time and insert non-recursive calls at compile time for the cases when the actual depth exceeds run time.

20- How many ways are there to initialize an int with a Constant?

There are two ways:

  • The first format uses traditional C notation.
    int result = 10;
  • The second format uses the constructor notation.
    int result (10);

21- What is a Constant? Explain with an example

A constant is an expression that has a fixed value. They can be divided into integer, decimal, floating-point, character or string constants depending on their data type.

Apart from the decimal, C++ also supports two more constants i.e. octal (to the base 8) and hexadecimal (to the base 16) constants.

Examples of Constants:

  • 75 //integer (decimal)
  • 0113 //octal
  • 0x4b //hexadecimal
  • 3.142 //floating point
  • ‘c’ //character constant
  • “Hello, World” //string constant

Note: When we have to represent a single character, we use single quotes and when we want to define a constant with more than one character, we use double-quotes.

22- How do you define/declare constants in C++?

In C++, we can define our own constants using the #define preprocessor directive.

#define Identifier value

Example:

include
 define PI 3.142
 int main ()
 {
                  float radius =5, area;
                  area = PI * r * r;
                  cout<<”Area of a Circle = “<<area;
 }

Output: Area of a Circle = 78.55

As shown in the above example, once we define a constant using #define directive, we can use it throughout the program and substitute its value.

We can declare constants in C++ using the “const” keyword. This way is similar to that of declaring a variable, but with a const prefix.

Examples of declaring a constant

const int pi = 3.142;
const char c = “sth”;
const zipcode = 411014;

In the above examples, whenever the type of a constant is not specified, the C++ compiler defaults it to an integer type.

23- Define token in C++.

A token in C++ can be a keyword, identifier, literal, constant and symbol.

24- Who was the creator of C++?

Bjarne Stroustrup.

25- What is Constructor and destructor in C++?

The constructor has been executed when the new objects of the class are created. It will have the same name exactly as the class name. A constructor can be the default constructor, which is not required to mention and it does not have any parameter. A constructor can be parametrized constructor that we need to mention or declare in class and parameters needs to be initialized.

Destructor has been executed when the objects of a class are not in scope or it’s no longer in use. It will have the same name exactly as the class name but should be prefixed with (~) sign. It is mainly used for releasing resources like a closing of files, etc.

26- What are virtual functions in C++?

This is the advanced C++ interview questions that are asked in an interview. It is mainly used to replace the implementation of the parent class. These are the functions that are declared in class with the keyword ‘virtual’.

When the parent class type reference is initialized with an object of child class type and overridden method (declared as virtual) is invoked using the parent class reference then the method of child class will get invoked.

27- Why do we need the Friend class and function?

Sometimes, there is a need for allowing a particular class to access private or protected members of a class. The solution is a friend class, which can access the protected and private members of the class in which it is declared as a friend.

Similar to the friend class, a friend function is able to access private and protected class members. A friend function can either be a global function or a method of some class.

Some important points about friend class and friend function:

  • Friendship is not inherited.
  • Friendship isn’t mutual, i.e., if some class called Friend is a friend of some other class called NotAFriend, then it doesn’t automatically become a friend of the Friend class.
  • The total number of friend classes and friend functions should be limited in a program as the overabundance of the same might lead to a depreciation of the concept of encapsulation of separate classes, which is an inherent and desirable quality of object-oriented programming.

28- How is function overloading different from operator overloading?

Function overloading allows two or more functions with different type and number of parameters to have the same name. On the other hand, operator overloading allows for redefining the way an operator works for user-defined types.

29- Is it possible for a C++ program to be compiled without the main() function?

Yes, it is possible. However, as the main() function is essential for the execution of the program, the program will stop after compiling and will not execute.

30- What is the difference between equal to (==) and Assignment Operator (=)?

In C++, equal to (==) and assignment operator (=) are two completely different operators.

Equal to (==) is an equality relational operator that evaluates two expressions to see if they are equal and returns true if they are equal and false if they are not.

The assignment operator (=) is used to assign a value to a variable. Hence, we can have a complex assignment operation inside the equality relational operator for evaluation.

31- Define ‘std’.

Std is the default namespace standard used in C++.

32- Which programming language’s unsatisfactory performance led to the discovery of C++?

C++was discovered in order to cope with the disadvantages of C.

33- How delete [] is different from delete?

Delete is used to release a unit of memory, delete[] is used to release an array.

34- Can we overload a destructor?

No, a destructor cannot be overloaded, and it has the only form without the parameters.

35- What is the default constructor?

The compiler provides a constructor to every class in case the provider does not offer the same. This is when the programmer provides the constructor with no specific parameters than it is called a default constructor. The code for default constructor can be displayed in the following example.

// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;
class construct {
public:
    int a, b;
    // Default Constructor
    construct()
    {
        a = 10;
        b = 20;
    }
};
int main()
{
    // Default constructor called automatically
    // when the object is created
    construct c;
    cout << "a: " << c.a << endl
         << "b: " << c.b;
    return 1;
} 

36- What is the difference between struct and class?

Structuresclass
A structure is a user-defined data type which contains variables of dissimilar data types.The class is a user-defined data type which contains member variables and member functions.
The variables of a structure are stored in the stack memory.The variables of a class are stored in the heap memory.
We cannot initialize the variables directly.We can initialize the member variables directly.
If access specifier is not specified, then by default the access specifier of the variable is “public”.If access specifier is not specified, then by default the access specifier of a variable is “private”.
The instance of a structure is a “structure variable”.
Declaration of a structure: struct structure_name { // body of structure; } ;Declaration of class: class class_name { // body of class; }
A structure is declared by using a struct keyword.The class is declared by using a class keyword.
The structure does not support the inheritance.The class supports the concept of inheritance.
The type of a structure is a value type.The type of a class is a reference type.

37- Draw a comparison between C++ and Java.

  • C++ has destructors, which are invoked automatically when an object is destroyed. Java has something called automatic garbage collection
  • It supports multiple inheritance, operator overloading, pointers, structures, templates, and unions. Java doesn’t have any of them
  • Java has a Thread class that is inherited in order to create a new thread. C++ has no inbuilt support for threads
  • A goto statement offers a way to jump from a location to some labeled statement in the same function. There is no goto statement in Java
  • It runs and compile using the compiler, which converts the source code into machine level language. Hence, it is platform-dependent. Java compiler, on the other hand, converts the source code into JVM bytecode, which is platform-independent.

38- What are the Extraction and Insertion operators in C++? Explain with examples.

In the iostream.h library of C++, cin, and cout are the two data streams that are used for input and output respectively. Cout is normally directed to the screen and cin is assigned to the keyboard.

“cin” (extraction operator): By using overloaded operator >> with cin stream, C++ handles the standard input.

int age;
cin>>age;

As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin (keyboard) to enter the data. “cin” processes the input only when the RETURN key is pressed.

“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It directs the data that followed it into the cout stream.

Example:

cout<<”Hello, World!”;
cout<<123;

39- What is the difference between an array and a list?

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

41- What does a Static member in C++ mean?

Denoted by the static keyword, a static member is allocated storage, in the static storage area, only once during the program lifetime. Some important facts pertaining to the static members are:

  • Any static member function can’t be virtual
  • Static member functions don’t have ‘this’ pointer
  • The const, const volatile, and volatile declaration aren’t available for static member functions

42- What is a mutable storage class specifier? How can they be used?

A mutable storage class specifier is applied only on the class’s non-static and non-constant member variable. It is used for altering the constant class object’s member by declaring it. This can be done by using a storage class specifier.

43- What do you mean by ‘void’ return type?

All functions should return a value as per the general syntax.

However, in case, if we don’t want a function to return any value, we use “void” to indicate that. This means that we use “void” to indicate that the function has no return value or it returns “void”.

Example:

void myfunc()
{
Cout<<”Hello,This is my function!!”;
}
int main()
{
myfunc();
return 0;
}

44- Explain Pass by Value and Pass by Reference.

While passing parameters to the function using “Pass by Value”, we pass a copy of the parameters to the function.

Hence, whatever modifications are made to the parameters in the called function are not passed back to the calling function. Thus the variables in the calling function remain unchanged.

Example:

void printFunc(int a,int b,int c)
{
a *=2;
b *=2;
c *=2;
}
 
int main()
 
{
 
int x = 1,y=3,z=4;
printFunc(x,y,z);
cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}

Output:

x=1
y=3
z=4

As seen above, although the parameters were changed in the called function, their values were not reflected in the calling function as they were passed by value.

However, if we want to get the changed values from the function back to the calling function, then we use the “Pass by Reference” technique.

To demonstrate this we modify the above program as follows:

void printFunc(int& a,int& b,int& c)
{
a *=2;
b *=2;
c *=2;
}
int main()
{
int x = 1,y=3,z=4;
printFunc(x,y,z);
cout<<”x = “<<x<<”\ny = “<<y<<”\nz = “<<z;
}

Output:
x=2
y=6
z=8

As shown above, the modifications done to the parameters in the called functions are passed to the calling function when we use the “Pass by reference” technique. This is because using this technique we do not pass a copy of the parameters but we actually pass the variable’s reference itself.

45- What is an overflow error?

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

46- What is overloading?

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

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

Overloading is of two types:

1. Operator overloading: Operator overloading is a compile-time polymorphism in which a standard operator is overloaded to provide a user-defined definition to it. For example, ‘+’ operator is overloaded to perform the addition operation on data types such as int, float, etc.

Operator overloading can be implemented in the following functions:

  • Member function
  • Non-member function
  • Friend function

Syntax of Operator overloading:

Return_type classname :: Operator Operator_symbol(argument_list)  
{  
      // body_statements;  
}  

2. Function overloading: Function overloading is also a type of compile-time polymorphism which can define a family of functions with the same name. The function would perform different operations based on the argument list in the function call. The function to be invoked depends on the number of arguments and the type of the arguments in the argument list.

47- What is the purpose of the “delete” operator?

The “delete” operator is used to release the dynamic memory created by “new” operator.

48- What are the differences between a shallow copy and a deep copy?

The differences between a shallow copy and a deep copy can be stated as under.

Shallow CopyDeep Copy
It allows memory dumping on a bit by bit basis from one object to another.It allows the copy field, which is done by field from one object to another.
It is achieved by using a copy instructor and an overloading assignment operator.It is used for shallow copy purposes.

49- Define an Abstract class in C++?

An abstract class in C++ is referred to as the base class, which has at least one pure virtual function. In such a function, a person cannot instantiate an abstract class. This way, an Abstract class a pure virtual function is defined by using a pure specifier which is equal to zero during the declaration of the virtual member function in the class declaration. The code sample can be displayed as follows in example.

// An abstract class
class Test
{
   // Data members of class
public:
   // Pure Virtual Function
   virtual void show() = 0;
  /* Other members */
};

50- Define Block scope variable?

A Block scope variable is the one that is specified as a block using the C++ that can be declared anywhere within the block.

51- What are the functions of the scope resolution operator?

The functions of the scope resolution operator include the following.

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

The code of the scope resolution operator can be displayed as follows.

#include <iostream>  
using namespace std; 
int my_var = 0;
int main(void) {
  int my_var = 0;
  ::my_var = 1;  // set global my_var to 1
  my_var = 2;    // set local my_var to 2
  cout << ::my_var << ", " << my_var;
  return 0;
}

52- What is the purpose of the Extern Storage Specifier?

“Extern” specifier is used to resolve the scope of a global symbol.

#include <iostream >
using nam espace std;
main()
{
extern int i;
cout<<i<<endl;
}
int i=20;

In the above code, “i” can be visible outside the file where it is defined.

53- Explain Register Storage Specifier.

“Register” variable should be used whenever the variable is used. When a variable is declared with a “register” specifier, then the compiler gives CPU register for its storage to speed up the lookup of the variable.

54- What is a Conversion Constructor?

It is a constructor that accepts one argument of a different type. Conversion constructors are mainly used for converting from one type to another.

55- What is an Explicit Constructor?

A conversion constructor is declared with the explicit keyword. The compiler does not use an explicit constructor to implement an implied conversion of types. Its purpose is reserved explicitly for construction.

56- What is the function of the keyword “Auto”?

The keyword “Auto” is used by default for various local variables to make function work automatically.

57- Name the Operators that cannot be Overloaded.

  • sizeof – sizeof operator
  • . – Dot operator
  • .* – dereferencing operator
  • -> – member dereferencing operator
  • :: – scope resolution operator
  • ?: – conditional operator

58- What is Exception Handling? Does C++ support Exception Handling?

Yes C++ supports exception handling.

We cannot ensure that code will execute normally at all times. There can be certain situations that might force the code written by us to malfunction, even though it’s error-free. This malfunctioning of code is called Exception.

When an exception has occurred, the compiler has to throw it so that we know an exception has occurred. When an exception has been thrown, the compiler has to ensure that it is handled properly, so that the program flow continues or terminates properly. This is called the handling of an exception.

Thus in C++, we have three keywords i.e. trythrow and catch which are in exception handling.

The general syntax for exception block is:

try{
…. 
# Code that is potentially about to throw exception goes here
….
throw exception;
}
catch(exception type) {

#code to handle exception goes here
}

As shown above, the code that might potentially malfunction is put under the try block. When code malfunctions, an exception is thrown. This exception is then caught under the catch block and is handled i.e. appropriate action is taken.

59- What is an Iterator class?

In C++ a container class is a collection of different objects.

If we need to traverse through this collection of objects, we cannot do it using simple index variables. Hence, we have a special class in STL called an Iterator class which can be used to step through the contents of the container class.

The various categories of iterators include input iterators, output iterators, forward iterators, bidirectional iterators, random access, etc.

60- What is the use of ‘using’ declaration?

Using Declaration is used to refer a name from the namespace without the scope resolution operator.


With this, we have come to the end of C++ interview questions blog. I Hope these C++ Interview Questions will help you in your interviews. You can also comment below if you have any questions in your mind, which you might face in your C++ interview.


Start learning HTMLCSS and JavaScript.

Test your skills with Amazing Quizzes.

Also Read :

Leave a Comment

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