Planforexams.com

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

Commonly asked C++ Coding Interview Questions & Answers

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++

3) What are the disadvantages of C++ ?

Below given are the advantages of C++

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

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++ ?

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

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++ ?

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:

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++

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 

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

The below given are the OOPs concepts in C++

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 can be classified into 2 categories:

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

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++:

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++

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++

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++ ?

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

#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 ? 

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++ ?

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++ ?

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++

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++ ?

#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++ ?

#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;
}
Exit mobile version