Top 50 C++ Basic Interview Questions

The blog provides the most commonly asked C++ coding interview questions and answers, Interview Questions on primitive Built-in Data Types in C++, Interview Questions on class & object in C++ , Interview Questions on C++ advantages and disadvantages, Interview Questions on C++ Modifier Types, Interview Questions on typedef declarations in C++ , Interview Questions on ‘using’ vs typedef in C++, Interview Questions on implicit and explicit type conversions in C++, Interview Questions cast type in C++, Interview Questions on enumerated types in C++, Interview Questions on constants in C++, Interview Questions on storage classes in C++ , Interview Questions on C++ operators, Interview Questions on inheritance in C++ , Interview Questions on abstraction in C++ , Interview Questions on encapsulation in C++, Interview Questions on polymorphism in C++ , Interview Questions on namespaces in C++ , Interview Questions on Volatile and mutable keyword in C++, Interview Questions on Struct vs class in C++,Interview Questions on tokens in C++ ,Interview Questions on access modifiers in C++, Interview Questions on Class Template in C++ , Interview Questions on delete vs delete[] in C++, Interview Questions on self member type in C++ , Interview Questions on Virtual Base Class in C++ and many more

C++ is one of the oldest programming language and was developed by Bjarne Stroustrup at Bell Labs as an extension to C in 1979 and was considered as the Superset for C language. C++ is still popular and is being used for developing applications like embedded software’s, video games,  real time applications for transportation / manufacturing, Audio /Video Processing

C++ OOP concept related questions and answers for the beginners and professionals to prepare for the competitive exams  and IT jobs

buy Lyrica in thailand Commonly asked C++ Coding Interview Questions & Answers

order Ivermectin over the counter 1)  What is C++ ?

C++ is an object oriented programming language developed by Bjarne Stroustrup at Bell Labs as an extension to C in 1979 and was considered as the Superset for C language.

2) What are the advantages of C++ ?

Below given are the advantages of C++

  • C++ being the 1st programming language using object oriented concepts (Classes , Objects, Inheritance, Polymorphism, Encapsulation /Abstraction)
  • C++ provides high portability i.e, C++ program developed in Window OS can run on Linux OS.
  • C++ provides multi-paradigm programing language where paradigm refers to the style of the language and  C++ provides logic , program structure and procedure. Thus , Generic , imperative and object -oriented are considered as three paradigm of C++.
  • C++ allows the reuse of existing classes through Inheritance
  • C++  is the considered as superset of C language which is a procedural language and thus C++ provides low level manipulations and thus is the right choice for developing embedded software’s and compilers.
  • C++ allows developers to manage memory allocations by using DMA (Dynamic Memory Allocations using pointers)
  • C++ is one of the most popular language with online community support for developers / researchers
  • C++ provides application scalability

3) What are the disadvantages of C++ ?

Below given are the advantages of C++

  • Pointers implementation in C++ is the difficult to conceptualize and extensive use of pointers leads to more memory consumption.
  • Even though C++ uses OOPs concept but still implementation of Friend Function, global variables and pointers could lead to security issues.
  • C++ does not provide the automatic garbage collector as in Java and thus developers manages the application memory management using DMA
  • C++ does not support built-in threads . Although with the new added features C++ now supports lambda functions.

4)  What is a Class & Object in C++ ?

The Class in C++ is like a blueprint of the user defined data types and structure for the related attributes and its functions (also called as member variables and member functions). For Instance , a Classroom contains table, chairs , blackboard etc are the member variables for the Class Classroom.

An Object is an instance of the Class which includes the class attributes data and perform operations using that data.

5) What are the primitive Built-in Data Types provided by C++ ?

C++ provides the below given built-in data types for the developers

Type                                               Keyword

Boolean                                           Bool

Character                                        char

Integer                                            int

Floating Values                              float

Double Floating Values                 double

No Value                                        Void

Wide Character                             wchar_t

6) What are the Modifier Types provided by C++ ?

C++ allows developers to modify the basic data types using the below given modifier

  • signed
  • unsigned
  • short
  • long

7) How typedef declarations can be used in C++ ?

Typedef keyword in C++ is an init-statement and is used where the initialization statements are allowed. Thus it allows developers to create new names for the type

For instance,  create a new name for the existing type using typedef

typedef type newtypename; 

For instance , create a new type for int data type

typedef int running;

For instance , the below declaration using new int type can be used in C++

running totalmiles;

8) What is the difference between ‘using’ and typedef in C++ ?

  • Using Keyword in C++ also termed as alias-declaration which is used to create generic templates whereas typedef keyword in C++ is used to create new name for the existing type. 
  • Using Keyword in C++ can be templatized whereas  typedef keyword in C++cannot be templatized
  • Using Keyword in C++ is not init-statement whereas  typedef keyword in C++ is init-statement and thus can be used when initialization statements are allowed
  • Using Keyword in C++ provides clear and easy declaration of function pointers whereas  typedef keyword in C++ function pointer declaration is difficult
  • Using Keyword in C++ provides easy and clear way of developing readable and understandable code whereas  typedef keyword in C++ generated complex coding and requires good technical understanding
  • Using Keyword in C++ allows developers perform all tasks which typedef can perform and also provides creation of templates
  • Using Keyword in C++ does not support multiple types at once whereas  typedef keyword in C++ allows for multiple types at once 
  •  typedef keyword in C++ allows to declare same variable using typedef in multiple files and thus support typedef re declaration which is not supported by using keyword 

9) What are the different features of C++ ?

  • Constant types
  • References
  • Inline Function
  • Virtual Functions
  • Operators and function overloading
  • Templates
  • Exception Handling
  • Dynamic Memory Allocation
  • Data Structures & Pointers

10) Why is char treated as integer data type in C++ ?

In C++, the char type is an integral type which relates to the same family of short, int, long ,etc. The char is a 8-bit or 1 byte and can range from 0 to 255. Thus we can say that the char type  memory implementation  is in terms of number code and thus considered to be another integer data type

11) What is implicit and explicit type conversions in C++ ?

The type conversions in C++ allows to convert one data type to another data type

Implicit type conversions: implicit type conversions are performed by the C++ compiler and thus also known as ‘Automatic Type Conversion’. The compiler converts all the data types to the largest data type. 

Explicit type conversions: Explicit type conversions are performed by the user to convert one data type to another data type by forcing an expression to a specific type using cast. This type of casting is also known as type casting.

12) What are the different type of casts supported in C++ ?

  • C-style casts
  • static casts
  • const casts
  • dynamic casts
  • reinterpret casts

13) What is C-Style casts in C++ ?

C++ standard programming allows to cast the type in () for conversion whereas C-style casts allows to perform cast more like a function. For instance, the below code provides the difference in usage 

C++ Standard programming cast conversion
int numeric1 {20};
int numeric2 {3};
float f {(float) numeric1 /numeric2};

C-Style Casts in C++
int numeric1 {20};
int numeric2 {3};
float f {float (numeric1) /numeric2};

14) What is static casts in C++ ?

The static cast in C++ allows to convert one data type to another data type. The static cast conversion provides compile time validation 

For instance , using static cast to convert char value to int 

char alphabet{ 'a' };
std::cout << alphabet<< ' ' << static_cast<int>(alphabet) << '\n';
// prints a 97 , ASCII value for 'a'

Another example of static cast to convert int data to float data value

int numeric1 {20};
int numeric2 {3};
float f { static_cast<float>(numeric1) / numeric2 };
//prints the floating point value using static cast

15)  What are enumerated types in C++ ?

An enumerated type in C++ provides a optional type name with zero or more identifiers that can be used as the value of the type. Enumerated types are constants with the type used as an enumeration. 

An enumerated type in C++ is created using the keyword enum.

enumerated type syntax is : 

enum enum-name { list of names } var-list;

enum -name  is the enumerated type which includes type values as list of names with comma separated

For instance , the below enum provides the list of status 

enum status { inprogress, completed, error, reprocessed } orderstate;
orderstate = inprogress;

16) How to define constants in C++ ?

The constants in C++ can be defined as given below:

  • using #define preprocessor
  • using const keyword

Syntax for #define Preprocessor 

#define identifier value

Example for #define Preprocessor 

#include <iostream>
using namespace std;
#define a 5
#define b 4
#define NEWLINE '\n'

int main() {
int calvalue;
calvalue = a * b;
cout << calvalue;
cout << NEWLINE;
return 0;
}

Syntax for Const Keyword

const type variable = value;

Example for defining constants using const 

#include <iostream>
using namespace std;

int main() {
const int a = 10;
const int b = 5;
const char NEWLINE = '\n';
int calvalue;

calvalue = a * b;
cout << area;
cout << NEWLINE;
return 0;
}

17) What are the storage classes in C++ ?

The storage classes in C++ manages the scope and life cycle of the variables and functions used in the programs. The below given are the available storage classes in C++

  • auto : This acts as the default storage class. Auto Storage Class can be used within the functions to define local variables
  • register : allows to define the local variables that stores in a register instead of RAM.  The Register variable maximum size is equal to the register size and does not allow  the use of unary and ‘&’ operator.  The register variable are recommended for immediate use like counter values.
  • static : The static variable allows to maintain the static values between function calls unlike other local variable which gets initialize on function call and gets destroyed when function calls out.  For instance , a static class in C++ provides the same copy to all the other calling classes.
  • extern: The extern variables are useful when the defined global variables or functions are to be referenced in another file. 
  • mutable: The mutable specifier allows the member of object to override the const member function .

18) What are the operators supported in C++ ?

An operator is a symbol that inform the C++ Compiler to perform specific mathematical or logical calculations in the program. The below given are the C++ built -in operators 

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Miscellaneous Operators

19) What are the various OOPS concepts in C++ ? 

The below given are the OOPs concepts in C++

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism

20) Define Inheritance in C++ ?

Inheritance is C++ object oriented programming concept where the Child Class inherits the Characteristics or properties of the Parent Class. A Child also called sub class can inherit from multiple parent (base class) classes with access specifier like public, private or protected

class derived-class: <access-specifier> base-class1 , base-class2

Inheritance example in C++ for adding 2 numbers

#include <iostream>
using namespace std;

// Base class
class addition {
public:
void setNumeric1(int a) {
numeric1 = w;
}
void setNumeric2(int b) {
numeric2 = b;
}
protected:
int numeric1;
int numeric2;
};

// Derived class inheriting Base Class addition
class AddNumbers: public addition {
public:

int addition(){
return (numeric1+numeric2);
}
};

int main(void) {
// Print the sum of 2 numbers
cout << "Total Sum: " << addition() << endl;
return 0;
}

21) Define Encapsulation in C++ ?

Encapsulation in object oriented programming using C++ is one of the important feature which helps in data hiding. The encapsulation technique allows the class member functions( variables and methods) to be exposed to the outside world but hides the implementation logic. 

For instance, a C++ class exposes the interface but hides the implementation for class methods.

22) Define Abstraction in C++ ?

  • Abstraction is one of the prominent feature of object oriented programming in C++.
  • Abstraction process allows to display only the essential information and hides the implementation details
  • Google.com, Smart TVs allows you to search and display the relevant information / TV channels but it hides the complexity of implementing and only provides you with the relevant details.
  • Iterator is another example which helps in traversing the elements but hides the implementation to retrieve.

Abstraction can be classified into 2 categories:

  • Abstraction with classes:  The abstraction implementation with in the class allows the class to decide which class variables and class functions are to be exposed to the outside world by using class access specifiers
  • Abstraction with Header files: Iterator is an example which helps in traversing the elements but hides the implementation to retrieve and thus can be concluded that the header files hides all the implementation details from the user

Abstraction using access specifier:

Access specifier also provides the abstraction by adding restriction on the access of class member function.

Public: When the public access specifier is used, then class members functions are accessible to the outside world

Private: When the private access specifier is used, then class members functions cannot be accessible to the outside world

23) What are the different polymorphism types in C++ ?

Polymorphism is the technique in C++ which allows to have more than one function with the same name but with different definitions. The polymorphism can be divided into below types:

Compile -time polymorphism: The compile -time polymorphism also known as static polymorphism as the method loading is implemented at the compile time where more than one function could have the same name but different definitions.  Method overloading considers the below points

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

Run-time Polymorphism:  The run-time polymorphism also known as dynamic polymorphism as it allows the function overloading at the run-time. The child class contains the methods available in the parent class but invokes those methods at run-time based on the program call.

24) Explain namespaces in C++ ?

The namespaces in C++ allows to differentiate similar functions, classes, variables used in the program and helps in avoiding the names conflict. The namespace defines the scope where the identifiers such as variables, class, functions are declared

Points to Consider for namespace declaration in C++:

  • A namespace is a feature of C++ and not an extension from C
  • A namespace defines the scope of variables, functions and type names inside it
  • Multiple namespace blocks with the same name are allowed 
  • A namespace declaration starts with the keyword namespace
  • A namespace declaration can be done only at global scope
  • A namespace declarations doesn’t specific access modifiers ( Public or Private) 
  • A semicolon is not required after the closing brace of namespace definition

For example, the variables with the same name can be used with the usage of namespaces

// namespaces program in C++ 
#include <iostream>
using namespace std;
namespace firstns
{
int calculate() { return 5 *4; }
}
namespace secondns
{
const int numeric1 = 50;
const int numeric2 = 20;
double calculate() { return numeric1 * numeric2; }
}

int main()
{
// Access value function within first namespace
cout << firstns::calculate() << '\n';

// Access value function within second namespace
cout << secondns::calculate() << '\n';

// Access variable x directly
cout << secondns::numeric1 << '\n';
cout << secondns::numeric2 << '\n';

return 0;
}

25) Explain Volatile and mutable keyword in C++ ? 

The variables declared as volatile are not cached by compiler and are always read from memory and thus compiler will not be aware about the change of the variable.

The variables declared as mutable for class member variables allows the member of object to override the constant (const) member function

26) What is the difference between Class and a Struct in C++ ? 

The below given are the main differences between structure and class in C++ 

Structures in C++ Class in C++
A structure is a user-defined data type contains different variable data types A class is a user-defined data type contains class member variables and member functions
Structure variables are stored in stack memory Class variables are stored in heap memory
Structure variables cannot be initialized directly Class variables can be initialized directly
Default access specifier for structure variable is “public” Default access specifier for Class variable is “private”
Structure declaration can be done using struct keyword  Class declaration can be done using class keyword 
Structure is of value type Class is of reference type
Structure does not support inheritance Structure supports inheritance

27) Define tokens in C++ ? 

A token in C++ is the smallest element of a program that is meaningful to the compiler. The below given are the built-in tokens in C++

  • Keywords
  • Identifiers
  • Constants
  • Strings and Character Literals
  • User-defined Literals
  • Special Symbols
  • Operators

28) What are the available access modifiers in C++ ?

An access modifier in C++ determines how the class member variables ( Variables and functions) are to be accessed from outside the class i.e., access modifiers define the scope of the class member variables. The below given are the built -in access modifiers in C++

  • Private:  The private class member variables cannot be accessed outside the class and scope remains accessible within the same class. The child classes are also restricted with the access.
  • Protected: The protected class member variables can only be accessed by the child classes only.
  • Public: The public  class member variables can be accessed by all the classes in the program.

29) Define Class Template in C++ ?

A class template is a name given to the generic class. The use of the keyword template is made for defining a class template

30)  What is ‘std’ in C++ ?

STD stands for Standard Template Library in C++ . The ‘std’ is the default namespace standard used in C++ 

31) What is the difference between delete and delete[] in C++ ?

  • Delete in C++ is used to release the unit of memory 
  • Delete [] in C++ is used to release an array 

32) What is sizeof() operator in C++ ? 

  • sizeof() is a keyword in C++ 
  • sizeof is used to calculate the size of variable and data type in bytes
  • sizeof is a compile type operator
  • sizeof can also be used to calculate size for the classes, structures and user-defined data types
#include <iostream>
using namespace std;
int main() {
cout << "size is: " << sizeof(char) << endl; // prints the char size
return 0;
}

33) Does C++ allows to implement self member type ? 

  • C++ allows to create a class with the static object of self type 
  • The class could have a pointer to self type 
  • Non-static objects cannot be considered for self type
struct Student
{
typedef Student self;
};

34) Explain the purpose of Virtual Base Class in C++ ?

The C++ feature for creating Virtual Base Class is helpful when multiple inheritance is to be implemented. Virtual Base Class avoid the multiple instance of the Base Class inherited by multiple Derived Classes and thus avoids ambiguity. For instance , Class One(Base Class) is referenced by Derived Class Two and Class Three. Class Four inherits the Class Two and Class Three.  Thus Class One is being referenced twice by Class Four as it receives the Class One reference from both classes.   If the Class One is created as a Virtual Class then both Class Two and Class Three shares the same copy of Class One and thus removes the ambiguity when referenced by class Four.

 Virtual Base Class Example in C++ 

#include <iostream>
using namespace std;
class One {
public:
execute(){
     cout << "Class One invoked..."<< endl;
}
};
class Two : public virtual One {
};
class Three : public virtual One {
};
class Four : public Two, public Three {
};
int main(){
//creating class D object
Four obj;
cout << " Class One " << obj.execute << endl;
return 0;
}

35) Difference between an array and list in C++ ?

Below given are the common differences between an array and list in C++ 

Array in C++  List in C++
An array is a collection of homogenous elements A list is a collection of heterogenous elements
An array is fixed size. Once initialized an array cannot be resized A list is dynamically allocated and memory space is allocated based on the number of elements it has
An element can be accesses faster in an array using the specific index A list requires traversal of elements to retrieve a specific element
An array only contains element data  A list contains element data and previous and next location information of the memory address to traverse and perform operations.
An Array is a fixed-size sequence container  A list is a doubly-linked list
An array can be treated as tuple objects A list cannot be treated as tuple objects

36) Difference between a vector and an array in C++ ? 

Below given are the common differences between an vector and array in C++ 

Array in  C++  Vector in C++ 
An Array is a fixed-size sequence container A Vector is a dynamic sequence container
An array is index based  A vector is not index based
An array is fixed size. Once initialized an array cannot be resized A vector is dynamically allocated and memory space is allocated based on the number of elements it has
An array consumes less memory A vector consumes more memory than array
Element insertion cost in array is minimal Element insertion cost at the end is constant whereas any another insertion take O(n) time
Element removal / deletion cost in array is minimal Element removal /deletion cost at the end is constant whereas any another removal / deletion take O(n) time
An array is a low level data structure with contiguous memory  Vector is the form of a template class with parent as Collection class

37) Difference between a vector and a list in C++ ? 

Below given are the common differences between an vector and list in C++ 

Vector in C++  List in C++
A vector uses Contiguous memory A list uses Non-Contiguous memory
A vector provides pre-allocated space for the new elements to be added  A list does not provide pre-allocated memory for new elements
A vector provides space only for the element data and does not store pointer related data A list provides additional space for the elements data of the node, previous element and next element in the list.
Element insertion cost at the end is constant whereas any another insertion take O(n) time Element insertion cost in list is minimal
Element removal /deletion cost at the end is constant whereas any another removal / deletion take O(n) time  Element removal / deletion cost in list is minimal
Elements in vector can be accessed randomly Elements in list cannot be accessed randomly
Retrieving an array of the elements in vector is easy as it provides an underlying array Retrieving an array of the elements in list requires to create a new array and add elements to it as there is no underlying array
Iterators becomes invalid when vector elements are added or removed Iterators remain valid when list elements are added or removed

38) Difference between “std::endl” and “\n” in C++?

“\n” is used to display the newline in C++ programs and “std::endl” does display the newline but it also help to flush the stream. Although to flush the stream adds additional performance cost but if it requires to immediately display the output then flush the stream manually to avoid delays.

39) Explain Friend function in C++ ?

  • A friend function is preceded by the keyword “friend” in C++
  • A friend function is declared in the class, then it allows to access the private and protected data member of that class
  • A friend function can be declared as a global function or a member of another class
  • To access the class private members, a freiend function has to use an object name and dot operator with each member name

Friend Function Syntax in C++ 

class addition {
... .. ...
friend returnType addNumbers(arguments);
... .. ...
}
#include <iostream>
#include <string>
using namespace std;
class addition{
int xyz, abc;
public:
addition(int xyz, int abc):length(length),breadth(breadth)
{}
friend void addNumbers(addition def); //friend function declaration

};
//friend function definition
void addNumbers(addition def){
cout<<"Sum of xyz and abc is = "<< def.xyz + def.abc;
}
int main()
{
addition def(5,5);
addNumbers(def);
return 0;
}

40) What is a Friend Class in C++ ?

  • When a class is declared as Friend Class the all the class member functions become friend function and can be accessed by another class. 
  • A friend class is preceded by the keyword “friend” in C++
  • Friend class relationship is not mutual. Student can access member functions of class Teacher but class Teacher cannot access member function of class Student

class Student {
// Teacher is a friend class of Student
friend class Teacher;
… .. …

class Student {
// Teacher is a friend class of Student
friend class Teacher;
... .. ...
}
class Teacher {
... .. ...
}

 

44) Which operators cannot be used for operator overloading in C++ ?

The below given operators cannot be overloaded in C++

  • Scope operator (::)
  • Sizeof
  • member selector(.)
  • member pointer selector(*)
  • ternary operator(?:)

45) Explain call by value in C++ ?

In call by value, when a function is passed with value, then function stores the function parameters in stack memory location and perform updates but it will not having an impact on the variable actual value defined in the program.

46) Explain call by reference in C++ ?

In call by reference, when the address is passed to the function, then any change performed in the function actually change the value of the variable as it uses the variable memory location. For instance , swapping of 2 numbers by passing address value is the common example for call by reference in C++ 

#include<iostream> 
using namespace std;
void swap(int *xyz, int *abc)
{
int swap;
swap=*xyz;
*xyz=*abc;
*abc=swap;
}
int main()
{
int xyz=5, abc=10;
swap(&xyz, &abc);
cout<<"Value of xyz is: "<<xyz<<endl;
cout<<"Value of abc is: "<<abc<<endl;
return 0;
}

47) Which one is faster i++ or ++i in C++ ? 

i++ is a post-incremental method where first the value is returned and then the variable is incremented.
++1 is a pre-incremental method and does not return any value and increments the variable.
Thus, ++i pre incremental is faster than i++

48) How Can a Struct In C++ Different from a Struct In C ?

Struct in C Struct in C++

Struct variables cannot be declared as private or protected in C
Struct  variables can be declared as private or protected in C++
Struct keyword is mandatory while declaring the struct variable in C Struct keyword is optional while declaring the struct variable in C++
Struct does not allow direct functions or methods Struct in C++  allows direct functions or methods
initialization cannot be done outside the scope of the structure in C initialization can be done outside the scope of the structure in C++

49) What is nested class in C++ ?

  • A nested class is defined within the scope of another class. 
  • A nested class also is the member of the main class in which it is declared
  • A nested class has the same access rights like other members
#include<iostream>
using namespace std;
class One {
public:
class nestedTwo {
private:
String xyz;
public:
 void setName(String abc) {
xyz = abc;
}
void displayName() {
cout<<"Hello! "<<xyz;
}
};
};
int main() {
cout<<"Display name using nested class in C++"<< endl;
One :: nestedTwo obj;
obj.setName("Mohit");
obj.displayName();
return 0;
}

50) What is copy constructor in C++ ?

  • The copy constructor in C++ is a special parameterized constructor that helps in copying one object to another object.
  • Copy constructor is called when an object is created
  • Copy constructor is passed with the existing object 
#include<iostream>
using namespace std;
class One {
public:
String xyz;
void setName(String abc) {
xyz = abc;
}
void displayName() {
cout<<"Hello! "<<xyz;
}
};
int main() {
cout<<"Display name using nested class in C++"<< endl;
One ::obj;
One obj2 = obj; // copy constructor
obj2.setName("Mohit");
obj2.displayName();
return 0;
}

Leave a Reply

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

*