C++ basics Interview Questions And Answers


C++ is a general-purpose programming language created by Bjarne Stroustrup that gives a clear structure to programs and allows code to be reused, lowering development costs. The language is an extension of the C programming language, or you can say that it is “C with Classes”. The language has significantly adopted object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. 

C++ code introduces object-oriented programming (OOP) to C and offers classes with four features: 

  • Abstraction: Using Abstraction, you only show the user relevant details and hide irrelevant details.
  • Encapsulation: Binds together the data and functions and keeps them safe from outside interference and misuse.
  • Inheritance: Helps the process in which one object acquires all the properties and behaviours of its parent object automatically.
  • Polymorphism: It is ability of a message that displays in more than one form.

Know More About C++

One distinguishing feature of C++ classes is support for deterministic destructors, which in turn provide support for the Resource Acquisition is Initialization (RAII).

C++ includes systems programming and embedded, resource-constrained software and large systems in mind. However, it is equally efficient for software infrastructure and resource-constrained applications that includes desktop applications, video games, servers and performance-critical applications (like telephone switches)

Facts about C++

Before you start with C++ interview questions and answers, here are some basic facts that all beginners should be aware of:

  • C++ is a cross-platform language. Also, you can use it to create high-performance applications such as Image Ready, Adobe Premier, Photoshop and Illustrator.
  • Bjarne Stroustrup made and updated it 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, and C++20.
  • The language offers you a high level of control over system resources and memory.
  • C++ is one of the world’s most popular programming languages. Also, you will find it in today’s operating systems, Graphical User Interfaces, and embedded systems.
  • C++ is portable. You can use it to develop applications that you can also use in multiple platforms. As the language is close to C, C# and also Java, you can easily switch to C++ or vice versa.

While you are ready to jump to our next section, C++ interview questions and answers, you must know the basic difference between C++ and C. 

No doubt that both languages have almost the same syntax, but the main difference between them is that C++ supports classes and objects while C does not.

What is the basic structure of a C++ program?

 The basic structure of a C++ program is:

#include<iostream.h>
int main()
{
                cout<<”Hello,World!”;
                return 0;
}


The first line that begins with “#” is a preprocessor directive. In this case, we are using include as a directive which tells the compiler to include a header. While as you use “iostream.h” for basic input/output later in the program.

The next line is the “main” function that returns an integer. The main function is the starting point of execution for any C++ program. Irrespective of its position in the source code file, the contents of the main function are always executed first by the C++ compiler.

In the next line, we can see open curly braces that indicate the start of a block of code. After this, we see the programming instruction or the line of code that uses the count which is the standard output stream (its definition is present in iostream.h).

This output stream takes a string of characters and prints it to a standard output device. In this case, it is, “Hello, World!”. Please note that each C++ instruction ends with a semicolon (;), which is very much necessary, and omitting it will result in compilation errors.

Before closing the braces}, we see another line “return 0;”. This is the returning point to the main function.

Every C++ program will have a basic structure as shown above with a preprocessor directive, the main function declaration followed by a block of code, and then a returning point to the main function which indicates successful execution of the program.

What are the Comments in C++?

Comments in C++ are simply a piece of source code that complier ignores. 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 “*/”.

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 the above Example,

Result = 10;

C = ‘A’;

These are valid definitions.

Comment on the Local and Global scope of a variable.

The scope of a variable is the extent of the program code within which the variable remains active i.e., you can declare, define, or work with.

There are two types of scope in C++:

  1. Local Scope: A variable has a local scope or is local when it is 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 <iostream.h>
Int globalResult=0; //global variable
int main()
{
Int localVar = 10; //local variable.
…..
 
}

What is the precedence when there is a Global variable and a Local variable in the program with the same name?

Whenever there is a local variable with the same name as that of a global variable, the compiler gives precedence to the local variable.

Example:

#include <iostream.h>
 int globalVar = 2;
int main()
{
 int globalVar = 5;
 cout<<globalVar<<endl;
}

The output of the above code is 5. This is because, although both the variables have the same name, the compiler has given preference to the local scope.

When there is a Global variable and a Local variable with the same name, how will you access the global variable?

 When there are two variables with the same name but different scopes, i.e. one is a local variable and the other is a global variable, the compiler will give preference to a local variable.

In order to access the global variable, we make use of a “scope resolution operator (::)”. Using this operator, we can access the value of the global variable.

Example:

#include<iostream.h>
int x= 10;
int main()
{
 int x= 2;
 cout<<”Global Variable x =<<::x;
 cout<<”\nlocal Variable x=<<x;
}

Output:

Global Variable x = 10

local Variable x= 2

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);

What is a Constant? Explain with an example.

A constant is an expression that has a fixed value. You can divide them 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

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<iostream.h>
#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.

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.

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

What are the various Arithmetic Operators in C++?

C++ supports the following arithmetic operators:

  • + addition
  • – subtraction
  • * multiplication
  • / division
  • % module

What is a class?

The class is a data type that user defines to declare the class. Also, the class contains data members and member functions, and the three modifiers: private, public, and protected control their access. The class also defines type definition of the category of objects. It defines a data type, but not the data itself; rather, it determines the data’s structure.

What are the advantages of C++?

C++ not only maintains all features of the C language but also improves virtual memory and introduces a myriad of benefits, such as:

  • C++ is a highly versatile programming language, which indicates that software written in it can run on almost any platform.
  • Classes, objects, inheritance, polymorphism, and abstraction are all elements of C++, which is an object-oriented programming language.
  • Inheritance is a principle in C++. The inheritance eliminates the redundant code and also retain preexisting classes.
  • Data hiding aids the programmer in implementing security applications that are not susceptible to hackers.
  • Message passing is a connectivity methodology that enables objects to interact with one another.
  • C++ has a vast library of functions.

Define tokens in C++.

A token is the smallest element of a program that the compiler can understand. Moreover, you can categorize tokens as follows:

  • Keywords
  • Identifiers
  • Constants
  • Strings
  • Special Symbols
  • Operators

What are the different data types present in C++?

There are 4 Data types present in C++, they are:

  • Primitive Datatype (basic datatype). Example- char, short, int, float, long, double, bool, etc.
  • Derived datatype. Example- array, pointer, etc.
  • Enumeration. Example- enum
  • User-defined data types. Example- structure, class, etc

What is Data binding and Abstraction?

Data Binding: Data binding is the method of constructing a link between both the application’s user interface and the information it shows. If the binding has the correct parameters and the information provides the appropriate notification, whenever the data has changed its value, the components that are connected to it instantly adapt to the change.

Data Abstraction: Data abstraction is a process of reducing an enormous amount of information to a simple representation of the whole. Abstraction is the process of diminishing something to a set of basic characteristics by eliminating or subtracting characteristics.

What is the difference between C and C++?

CC++
C is a procedure-oriented programming language.C++ is an object-oriented programming language.
C does not support Data hiding.Encapsulation hides data to guarantee that data structures and operators are used correctly.
C is a subset if C++.C++ is a superset of C.
Overloading of functions and operators is not possible in C.Overloading of functions and operators is possible in C++.
In C, there are no namespace characteristics.C++ makes use of namespace to avoid name clashes.

What is the object in C++?

A class’s instance is an object. Because a class is a user-defined data type, it’s possible to refer to an object as a variable of that data type.

Explain what are the characteristics of Class Members in C++?

  • In C++, data and functions are members.
  • It is essential to define data members and methods within the class declaration.
  • You cannot re-declare member within a class.
  • You cannot add any other member outside of the class specification.

Discuss the difference between prefix and postfix.

In computing, there are two notations: prefix and postfix. The distinction between prefix and postfix notation is that the prefix writes the operator before the operands, whereas the postfix writes the operator after the operands.

What is the difference between struct and class?

StructureClass
By default, the structure’s members are open to the public.By default, members of the class are private.
When creating a struct from a class/struct, the underlying class/default struct’s access specifiers are public.Default access specifiers are private when deriving a class.
Declaration of a structure:struct structure_name{   // body of structure;} ;Declaration of class:class class_name{   // body of class;}

What is polymorphism in C++?

Polymorphism is defined as the presence of several forms. Its function depends greatly upon the circumstances. While we have several classes which are connected to each other through inheritance, this happens.

Consider a base class named car, which has a method called car brand (). Mercedes, BMW, and Audi are examples of derived automobile classes, and each has its own implementation of a car. 

Polymorphism has two types,

  • Compile Time Polymorphism.
  • Runtime Polymorphism.

What is operator overloading?

Operator overloading is a necessary component for performing operations on user-defined data types. We can change the default meaning of operators like +, -, *, /, =, and so on by overloading them.

For example,

Using operator overloading, the following code adds two complex numbers:

class complex{
private:
 float r, i;
public:
 complex(float r, float i){
  this->r=r;
  this->i=i;
 }
 complex(){}
 void displaydata(){
  cout<<”real part =<<r<<endl;
  cout<<”imaginary part =<<i<<endl;
 }
 complex operator+(complex c){
  return complex(r+c.r, i+c.i);
 }
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}

What is the difference between reference and pointer?

ReferencePointer
Reference is a temporary variable that acts like an alias for an existing variable.A pointer is a variable that stores a variable’s address.
To retrieve the value of a reference variable, no indirection operator is required. The value of a reference variable can be accessed directly.To get to the value of a pointer variable, you’ll need to use an indirection operator.
The reference variable cannot be reassigned with various address values once it has been assigned.Because the pointer variable is an independent variable, it can be renamed to point to various objects.
The reference variable cannot have a null value applied to it.The reference variable can be given a null value.
At the moment of declaration, the variable must be initialised.The variable does not need to be initialised at the moment of declaration.

What are access modifiers?

C++ has three access modifiers: public, private, and protected. Data hiding is one of the most important characteristics of object-oriented programming languages like C++. Data hiding refers to limiting access to a class’s data members.

Explain what is the use of void main () in C++ language?

The void main() specifies that the function will not return any value, whereas the int main() specifies that the function can return data of the integer type. We can utilise the void main when our programme is basic and will not terminate before reaching the last line of code, or when the code is error-free ().

Explain constructor in C++

When an object is formed, the function Object() { [native code] } is a member function that is called automatically. Constructors have the same name as the class they belong to, so the compiler recognises the member function as a function Object() { [native code] }. Constructors also don’t have a return type.

Example:

class A{
 private:
  int val;
 public:
  A(int x){             //one argument constructor
   val=x;
  }
  A(){                    //zero argument constructor
  }
}
int main(){
 A a(3);     

 return 0;
}

What are destructors in C++?

When an object is created for the first time, the function Object() { [native code] } is automatically invoked. Similarly, when an object is destroyed, a destructor function is automatically invoked. A destructor is preceded by a tilde and has the same name as the function Object() { [native code] } (which is the same as the class name).

Example:

class A{
 private:
  int val;
 public:
  A(int x){           
   val=x;
  }
  A(){                
  }
  ~A(){                  //destructor
  }
}
int main(){
 A a(3);     
 return 0;
}

What are the various OOPs concepts in C++?

The various OOPs Concepts in C++,

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Define virtual function

  • To replace the implementations provided by the base class, a virtual function is used. Even if the object in question is accessed via a base pointer rather than a derived pointer, the substitution has always been called when the object in question is of the derived class.
  • A virtual function is a member function that is defined by the derived class but is present in the base class.
  • When the same function name is used in both the base and derived classes, the base class function is declared with the keyword virtual.
  • Whenever a function is declared virtual, C++ determines which function to call at runtime based on the type of object referenced by the base class pointer. By altering the base class pointer to point to distinct objects, we can execute many copies of the virtual functions.

What is the purpose of the “delete” operator?

An object’s delete operation removes a specified property. If the deletion is successful, it will return true; otherwise, it will return false.

What is the difference between delete and delete[]?

Delete [] releases an array of allocated memory that was allocated with new[], whereas delete releases a single chunk of memory that was allocated with new.

What is a class template?

A class template specifies how classes are generated based on parameters. Containers are typically implemented using class templates. A class template is created by providing it with a set of types as template parameters.

What is call by value and call by reference in C++?

Call by value: We transmit a copy of the parameter to the functions when using the call by value approach. A new memory is assigned to these duplicated values, and changes to these values do not affect the variable in the main function.

Call by reference: We supply the address of the variable to the call by reference technique, and the address is utilised to retrieve the actual argument used in the function call. As a result, changes to the parameter affect the passing argument.

What is encapsulation?

Encapsulation is the process of binding together the data and functions in a class. It is applied to prevent direct access to the data for security reasons. The functions of a class are applied for this purpose.

What is the access specifier and what are the types?

An access specifier determines how the class members, i.e., functions and variables, will be accessed outside the class’s scope. 

There are three types of access specifiers in C++:

  • Private: Such class members can’t be accessed outside the class in which they are declared and are only accessible within the same class. Even child classes are disabled to access private members of its parent class.
  • Protected: In addition to the class in which they are declared, the child classes can access its parent class’s protected members.
  • Public: Class members declared as public can be accessed throughout the program.

What is a namespace?

A namespace is used for resolving the name conflict of the identifier, which is accomplished by placing them under various namespaces.

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.

What is a storage class?

A storage class in C++ specifically resembles the scope of symbols, including the variables, functions, etc. Some of the storage class names in C++ include mutable, auto, static, extern, register, etc.

What is an Inline Function? Is it possible to ignore inlining?

In order to reduce the function call overhead, C++ offers inline functions. As the name suggests, an inline function is expanded in line when it is called.

As soon as the inline function is called, the whole code of the same gets either inserted or substituted at the particular point of the inline function call. The substitution is completed by the C++ compiler at compile time. Small inline functions might increase program efficiency.

The syntax of a typical inline function is:

Inline return-type function-name(parameters)
{
// Function code goes here
}

As the inlining is a request, not a command, the compiler can ignore it.

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.

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 riend 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.

Explain vTable and vptr.

vTable is a table containing function pointers. Every class has a vTable. vptr is a pointer to vTable. Each object has a vptr. In order to maintain and use vptr and vTable, the C++ compiler adds additional code at two places:

  1. In every constructor – This code sets vptr:
    1. Of the object being created
    2. To point to vTable of the class
  2. Code with the polymorphic functional call – At every location where a polymorphic call is made, the compiler inserts code in order to first look for vptr using the base class pointer or reference. The vTable of a derived class can be accessed once the vptr is successfully fetched. The address of the derived class function show() is accessed and called using the vTable.

Explain the Copy Constructor.

A member function that initializes an object using another object of the same class is known as a copy constructor in C++. They can also be made private. A call to the copy constructor can happen in any of the following 4 scenarios when:

  1. The compiler generates a temporary object
  2. An object is constructed or based on some another object of the same class
  3. An object of the class is returned by value
  4. An object of the class is passed (i.e., to a function) by value as an argument

The general function prototype for the Copy Constructor is:

ClassName (const ClassName &old_obj);
Point(int x1, int y1) { x=x1; y=y1;}
Point(const Point &p2) { x=p2.x; y=p2.y; }

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

The differences between a shallow copy and a deep copy are:

Shallow CopyDeep Copy
Allows memory dumping on a bit-by-bit basis from one object to anotherAllows the copy field, which is done by field from one object to another.
Reflects changes made to the new/copied object in the original object. Doesn’t reflect changes made to the new/copied object in the original object.

What is an Abstract class?

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, 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 */
};

What are the functions of the scope resolution operator?

The functions of the scope resolution operator include the following.

  1. It helps resolve the scope of various global variables.
  2. It helps associate 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; // setlocal my_var to 2
cout << ::my_var << ", " << my_var;
return 0;
}

What is the ‘diamond problem’ that occurs with multiple inheritance in C++?

The diamond problem in C++ represents the inability of the programming language to support hybrid inheritance using multiple and hierarchical inheritance.

Suppose we have a university with some faculty members and some graduate students. A simple inheritance scheme in this scenario might have different types of people in different roles. However, all of them inherit from the same Person class.

The Person class defines an abstract getRole() method that would then be overridden by its subclasses in order to return the correct role type. Things up to this point are simple. However, if we wish to model the role of a TA or Teaching Assistant then things get more complex.

A Teaching Assistant is both a student and a faculty member. The problem generates an inheritance diagram resembling a diamond, hence the name, diamond problem.

Which getRole() implementation should the Teaching Assistant inherit? Graduate Student or Faculty Member? A potential answer might be to have the Teaching Assistant class override the getRole() method and return a newly-defined role, say TA.

However, such an answer would also be far from complete as it will hide the fact that a teaching assistant is both a faculty member and a graduate student.

How would you deallocate and allocate memory in C++?

The heap is used in C to allocate dynamic memory, and these functions are part of the standard library. Malloc() and free are the two important dynamic memory operations (). The size of the desired memory area in bytes is the only parameter accepted by the malloc() function. 

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main() {
  char *user;
  user = (char *) malloc(25);
  strcpy(user, "Jane_Eyre");
  cout << "User Name = " << user << " " << &user << endl;
  free(user);
}

What should be the correct statement about string objects in C++?

  1. String objects should necessarily be terminated by a null character
  2. String objects have a static size
  3. String objects have a dynamic size
  4. String objects use extra memory than required 
  5. String objects have a dynamic size.