C++ Interview
C++ Interview
C++ Interview
A list of top frequently asked C++ interview questions and answers are given below.
1) What is C++?
Initially, Stroustrup called the new language "C with classes". However, after sometime the name
was changed to C++. The idea of C++ comes from the C increment operator ++.
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.
C C++
C language was developed by Dennis Ritchie. C++ language was developed by Bjarne
Stroustrup.
In C language, data and functions are the free In the C++ language, both data and functions
entities. are encapsulated together in the form of a
project.
C does not support the data hiding. C++ supports data hiding. Therefore, the data
Therefore, the data can be used by the cannot be accessed by the outside world.
outside world.
C supports neither function nor operator C++ supports both function and operator
overloading. overloading.
In C, the function cannot be implemented In the C++, the function can be implemented
inside the structures. inside the structures.
Reference variables are not supported in C C++ supports the reference variables.
language.
C language does not support the virtual and C++ supports both virtual and friend functions.
friend functions.
In C, scanf() and printf() are mainly used for C++ mainly uses stream cin and cout to perform
input/output. input and output operations.
Reference Pointer
Reference behaves like an alias for an existing The pointer is a variable which stores the
variable, i.e., it is a temporary variable. address of a variable.
Reference variable does not require any indirection Pointer variable requires an indirection
operator to access the value. A reference variable operator to access the value of a variable.
can be used directly to access the value.
Once the reference variable is assigned, then it The pointer variable is an independent
cannot be reassigned with different address values. variable means that it can be reassigned
to point to different objects.
A null value cannot be assigned to the reference A null value can be assigned to the
variable. reference variable.
It is necessary to initialize the variable at the time of It is not necessary to initialize the variable
declaration. at the time of declaration.
5) What is a class?
The class is a user-defined data type. The class is declared with the keyword class. The class contains
the data members, and member functions whose access is defined by the three modifiers are
private, public and protected. The class defines the type definition of the category of things. It
defines a datatype, but it does not define the data it just specifies the structure of data.
Class:
The class is a user-defined data type which defines its properties and its functions. For example,
Human being is a class. The body parts of a human being are its properties, and the actions
performed by the body parts are known as functions. The class does not occupy any memory space.
Therefore, we can say that the class is the only logical representation of the data.
class student
{
//data members;
//Member functions
}
Object:
An object is a run-time entity. An object is the instance of the class. An object can represent a
person, place or any other item. An object can operate on both data members and member
functions. The class does not occupy any memory space. When an object is created using a new
keyword, then space is allocated for the variable in a heap, and the starting address is stored in the
stack memory. When an object is created without a new keyword, then space is not allocated in the
heap memory, and the object contains the null value in the stack.
class Student
{
//data members;
//Member functions
}
Inheritance:
Inheritance provides reusability. Reusability means that one can use the functionalities of the
existing class. It eliminates the redundancy of code. Inheritance is a technique of deriving a new
class from the old class. The old class is known as the base class, and the new class is known as
derived class.
Syntax
Encapsulation:
Encapsulation is a technique of wrapping the data members and member functions in a single unit.
It binds the data within a class, and no outside method can access the data. If the data member is
private, then the member function can only access the data.
Abstraction:
Data binding:
Data binding is a process of binding the application UI and business logic. Any change made in the
business logic will reflect directly to the application UI.
Polymorphism:
Polymorphism means multiple forms. Polymorphism means having more than one function with the
same name but with different functionalities. Polymorphism is of two types:
Polymorphism: Polymorphism means multiple forms. It means having more than one function with
the same function name but with different functionalities.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show()
{
cout<<"javaTpoint";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"javaTpoint tutorial";
}
};
int main()
{
Base* b;
Derived d;
b=&d;
b->show();
return 0;
}
Output:
javaTpoint tutorial
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.
IT experts needed
#include <iostream>
using namespace std;
class Multiply
{
public:
int mul(int a,int b)
{
return(a*b);
}
int mul(int a,int b,int c)
{
return(a*b*c);
}
};
int main()
{
Multiply multi;
int res1,res2;
res1=multi.mul(2,3);
res2=multi.mul(2,3,4);
cout<<"\n";
cout<<res1;
cout<<"\n";
cout<<res2;
return 0;
}
Output:
6
24
In the above example, mul() is an overloaded function with the different number of
parameters.
The namespace is a logical division of the code which is designed to stop the naming conflict.
The namespace defines the scope where the identifiers such as variables, class, functions are
declared.
The main purpose of using namespace in C++ is to remove the ambiguity. Ambiquity occurs
when the different task occurs with the same name.
For example: if there are two functions exist with the same name such as add(). In order to
prevent this ambiguity, the namespace is used. Functions are declared in different
namespaces.
C++ consists of a standard namespace, i.e., std which contains inbuilt classes and functions.
So, by using the statement "using namespace std;" includes the namespace "std" in our
program.
Syntax of namespace:
namespace namespace_name
{
//body of namespace;
}
namespace_name::member_name;
#include <iostream>
using namespace std;
namespace addition
{
int a=5;
int b=5;
int add()
{
return(a+b);
}
}
int main() {
int result;
result=addition::add();
cout<<result;
return 0;
}
Output:
10
Bjarne Stroustrup.
1. Pre-increment pointer: The pre-increment operator increments the operand by 1, and the value
of the expression becomes the resulting value of the incremented. Suppose ptr is a pointer then
pre-increment pointer is represented as ++ptr.
#include <iostream>
using namespace std;
int main()
{
int a[5]={1,2,3,4,5};
int *ptr;
ptr=&a[0];
cout<<"Value of *ptr is : "<<*ptr<<"\n";
cout<<"Value of *++ptr : "<<*++ptr;
return 0;
}
Output:
Value of *ptr is : 1
Value of *++ptr : 2
2. Post-increment pointer: The post-increment operator increments the operand by 1, but the
value of the expression will be the value of the operand prior to the incremented value of the
operand. Suppose ptr is a pointer then post-increment pointer is represented as ptr++.
#include <iostream>
using namespace std;
int main()
{
int a[5]={1,2,3,4,5};
int *ptr;
ptr=&a[0];
cout<<"Value of *ptr is : "<<*ptr<<"\n";
cout<<"Value of *ptr++ : "<<*ptr++;
return 0;
}
Output:
Value of *ptr is : 1
Value of *ptr++ : 1
Subtracting a pointer from another pointer: When two pointers pointing to the members
of an array are subtracted, then the number of elements present between the two members
are returned.
The Object is the instance of a class. A class provides a blueprint for objects. So you can create an
object from a class. The objects of a class are declared with the same sort of declaration that we
declare variables of basic types.
The access specifiers are used to define how to functions and variables can be accessed outside the
class.
Private: Functions and variables declared as private can be accessed only within the same
class, and they cannot be accessed outside the class they are declared.
Public: Functions and variables declared under public can be accessed from anywhere.
Protected: Functions and variables declared as protected cannot be accessed outside the
class except a child class. This specifier is generally used in inheritance.
18) What is Object Oriented Programming (OOP)?
OOP is a methodology or paradigm that provides many concepts. The basic concepts of Object
Oriented Programming are given below:
Classes and Objects: Classes are used to specify the structure of the data. They define the data
type. You can create any number of objects from a class. Objects are the instances of classes.
Encapsulation: Encapsulation is a mechanism which binds the data and associated operations
together and thus hides the data from the outside world. Encapsulation is also known as data
hiding. In C++, It is achieved using the access specifiers, i.e., public, private and protected.
Abstraction: Abstraction is used to hide the internal implementations and show only the necessary
details to the outer world. Data abstraction is implemented using interfaces and abstract classes in
C++.
Some people confused about Encapsulation and abstraction, but they both are different.
Inheritance: Inheritance is used to inherit the property of one class into another class. It facilitates
you to define one class in term of another class.
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.
20) What is the difference between new() and malloc()?
There is no need to allocate the memory while using "new" but in malloc() you have to use
sizeof().
"new" initializes the new memory to 0 while malloc() gives random value in the newly allotted
memory location.
The new() operator allocates the memory and calls the constructor for the object initialization
and malloc() function allocates the memory but does not call the constructor for the object
initialization.
The new() operator is faster than the malloc() function as operator is faster than the function.
Friend function acts as a friend of the class. It can access the private and protected members of the
class. The friend function is not a member of the class, but it must be listed in the class definition.
The non-member function cannot access the private data of the class. Sometimes, it is necessary for
the non-member function to access the data. The friend function is a non-member function and has
the ability to access the private data of the class.
To make an outside function friendly to the class, we need to declare the function as a friend
of the class as shown below:
class sample
{
// data members;
public:
friend void abc(void);
};
Since it is not in the scope of the class, so it cannot be called by using the object of the class.
Therefore, friend function can be invoked like a normal function.
A friend function cannot access the private members directly, it has to use an object name
and dot operator with each member name.
#include <iostream>
using namespace std;
class Addition
{
int a=5;
int b=6;
public:
friend int add(Addition a1)
{
return(a1.a+a1.b);
}
};
int main()
{
int result;
Addition a1;
result=add(a1);
cout<<result;
return 0;
}
Output:
11
23) What is a virtual function?
A virtual function is used to replace the implementation provided by the base class. The
replacement is always called whenever the object in question is actually of the derived class,
even if the object is accessed by a base pointer rather than a derived pointer.
A virtual function is a member function which is present in the base class and redefined by
the derived class.
When we use the same function name in both base and derived class, the function in base
class is declared with a keyword virtual.
When the function is made virtual, then C++ determines at run-time which function is to be
called based on the type of the object pointed by the base class pointer. Thus, by making the
base class pointer to point different objects, we can execute different versions of the virtual
functions.
C++ does not contain virtual constructors but can have a virtual destructor.
1. Never
2. Rarely
3. If you find that the problem domain cannot be accurately modeled any other way.
A Destructor is used to delete any extra resources allocated by the object. A destructor function is
called automatically once the object goes out of the scope.
Rules of destructor:
Destructors have the same name as class name and it is preceded by tilde.
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.
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.
Member function
Non-member function
Friend function
If you inherit a class into a derived class and provide a definition for one of the base class's function
again inside the derived class, then this function is called overridden function, and this mechanism is
known as function overriding.
Virtual inheritance facilitates you to create only one copy of each object even if the object appears
more than one in the hierarchy.
A Constructor is a special method that initializes an object. Its name must be same as class name.
The "delete" operator is used to release the dynamic memory created by "new" operator.
A scope resolution operator(::) is used to define the member function outside the class.
Delete [] is used to release the array of allocated memory which was allocated using new[] whereas
delete is used to release one chunk of memory which was allocated using new.
35) What is a pure virtual function?
The pure virtual function is a virtual function which does not contain any definition. The normal
function is preceded with a keyword virtual. The pure virtual function ends with 0.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show()=0;
};
Output:
javaTpoint
Structures class
A structure is a user-defined data type which The class is a user-defined data type which
contains variables of dissimilar data types. contains member variables and member
functions.
The variables of a structure are stored in the The variables of a class are stored in the heap
stack memory. memory.
We cannot initialize the variables directly. We can initialize the member variables
directly.
If access specifier is not specified, then by default If access specifier is not specified, then by
the access specifier of the variable is "public". default the access specifier of a variable is
"private".
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) What is a class template?
A class template is used to create a family of classes and functions. For example, we can create a
template of an array class which will enable us to create an array of various types such as int, float,
char, etc. Similarly, we can create a template for a function, suppose we have a function add(), then
we can create multiple versions of add().
template<class T>
class classname
{
// body of class;
};
classname<type> objectname(arglist);
Function overloading: Function overloading is defined as we can have more than one version of
the same function. The versions of a function will have different signature means that they have a
different set of parameters.
Operator overloading: Operator overloading is defined as the standard operator can be redefined
so that it has a different meaning when applied to the instances of a class.
A virtual destructor in C++ is used in the base class so that the derived class object can also be
destroyed. A virtual destructor is declared by using the ~ tilde operator and then virtual keyword
before the constructor.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructor is called"<<"\n";
}
~Base()
{
cout<<"Base class object is destroyed"<<"\n";
}
};
class Derived:public Base
{
public:
Derived()
{
cout<<"Derived class constructor is called"<<"\n";
}
~Derived()
{
cout<<"Derived class object is destroyed"<<"\n";
}
};
int main()
{
Base* b= new Derived;
delete b;
return 0;
Output:
MetroOpinion
OPEN
Earn $3.5 per answer
In the above example, delete b will only call the base class destructor due to which derived class
destructor remains undestroyed. This leads to the memory leak.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout<<"Base constructor is called"<<"\n";
}
virtual ~Base()
{
cout<<"Base class object is destroyed"<<"\n";
}
};
class Derived:public Base
{
public:
Derived()
{
cout<<"Derived class constructor is called"<<"\n";
}
~Derived()
{
cout<<"Derived class object is destroyed"<<"\n";
}
};
int main()
{
Base* b= new Derived;
delete b;
return 0;
Output:
When we use the virtual destructor, then the derived class destructor is called first, and then the
base class destructor is called.