C++ Programming Interview Question
C++ Programming Interview Question
Answer:
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 ++.
Answer:
C++ doesn't only maintains all aspects from C language, it also simplifies memory management
and adds several features like:
o C++ is a highly portable language means that the software developed using C++ language
can run on any platform.
o C++ is an object-oriented programming language which includes the concepts such as
classes, objects, inheritance, polymorphism, abstraction.
o C++ has the concept of inheritance. Through inheritance, one can eliminate the redundant
code and can reuse the existing classes.
o Data hiding helps the programmer to build secure programs so that the program cannot be
attacked by the invaders.
o Message passing is a technique used for communication between the objects.
o C++ contains a rich function library.
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 are
entities. encapsulated together in the form of a project.
C does not support the data hiding. Therefore, C++ supports data hiding. Therefore, the data
the data can be used by the outside world. cannot be accessed by the outside world.
C supports neither function nor operator C++ supports both function and operator
overloading. overloading.
In C, the function cannot be implemented inside In the C++, the function can be implemented inside
the structures. 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.
Answer:
Reference behaves like an alias for an existing variable, The pointer is a variable which stores the
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 can operator to access the value of a variable.
be used directly to access the value.
Once the reference variable is assigned, then it cannot The pointer variable is an independent
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 reference
variable. variable.
It is necessary to initialize the variable at the time of It is not necessary to initialize the variable at
declaration. the time of declaration.
Answer:
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.
Answer:
o Class:
o Object:
o Inheritance:
o Encapsulation:
o Abstraction:
o Data binding:
o Polymorphism:
Answer:
Answer:
o The namespace is a logical division of the code which is designed to stop the naming
conflict.
o The namespace defines the scope where the identifiers such as variables, class, functions
are declared.
o The main purpose of using namespace in C++ is to remove the ambiguity. Ambiquity
occurs when the different task occurs with the same name.
o 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.
o 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:
1. namespace namespace_name
2. {
3. //body of namespace;
4. }
Q9. Define token in C++.
Answer:
Answer:
Bjarne Stroustrup.
Answer:
Answer:
Answer:
Answer:
Answer:
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.
Answer:
The access specifiers are used to define how to functions and variables can be accessed outside
the class.
o 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.
o Public: Functions and variables declared under public can be accessed from anywhere.
o Protected: Functions and variables declared as protected cannot be accessed outside the
class except a child class. This specifier is generally used in inheritance.
Answer:
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.
Answer:
Answer:
Answer:
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:
1. class sample
2. {
3. // data members;
4. public:
5. friend void abc(void);
6. };
Answer:
o 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.
o A virtual function is a member function which is present in the base class and redefined
by the derived class.
o When we use the same function name in both base and derived class, the function in base
class is declared with a keyword virtual.
o 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.
Rules of a virtual function:
o The virtual functions should be a member of some class.
o The virtual function cannot be a static member.
o Virtual functions are called by using the object pointer.
o It can be a friend of another class.
o C++ does not contain virtual constructors but can have a virtual destructor.
Answer:
1. Never
2. Rarely
3. If you find that the problem domain cannot be accurately modeled any other way.
Answer:
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:
o Destructors have the same name as class name and it is preceded by tilde.
o It does not contain any argument and no return type.
Answer:
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.
Answer:
o 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.
o 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.
Answer:
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.
Answer:
Virtual inheritance facilitates you to create only one copy of each object even if the object
appears more than one in the hierarchy.
Answer:
A Constructor is a special method that initializes an object. Its name must be same as class name.
Answer:
The "delete" operator is used to release the dynamic memory created by "new" operator.
Answer:
Answer:
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.
Q34. What is the difference between struct and class?
Answer:
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 stack The variables of a class are stored in the heap
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.
Answer:
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().
The syntax of a class template:
1. template<class T>
2. class classname
3. {
4. // body of class;
5. };
Q36. What is the difference between function overloading and operator overloading?
Answer:
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.
Answer:
Comments in C++ are simply a piece of source code ignored by the compiler. They are only
helpful for a programmer to add a description or additional information about their source code.
Answer:
The declaration of a variable is merely specifying the data type of a variable and the variable
name. As a result of the declaration, we tell the compiler to reserve the space for a variable in the
memory according to the data type specified.
Example:
int Result;
char c;
int a,b,c;
All the above are valid declarations. Also, note that as a result of the declaration, the value of the
variable is undetermined.
Whereas, a definition is an implementation/instantiation of the declared variable where we tie up
appropriate value to the declared variable so that the linker will be able to link references to the
appropriate entities.
From above Example,
Result = 10;
C = ‘A’;
These are valid definitions.
Answer:
The scope of a variable is defined as the extent of the program code within which the variable
remains active i.e. it can be declared, defined or worked with.
Q40. What is the precedence when there are a Global variable and a Local variable in the
program with the same name?
Answer:
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
Q41. How many ways are there to initialize an int with a Constant?
Answer:
Answer:
In C++, equal to (==) and assignment operator (=) are two completely different operators.
Equal to (==) is an equality relational operator that evaluates two expressions to see if they are
equal and returns true if they are equal and false if they are not.
The assignment operator (=) is used to assign a value to a variable. Hence, we can have a
complex assignment operation inside the equality relational operator for evaluation.
Answer:
Q44. What are the Extraction and Insertion operators in C++? Explain with examples.
Answer:
In the iostream.h library of C++, cin, and cout are the two data streams that are used for input
and output respectively. Cout is normally directed to the screen and cin is assigned to the
keyboard.
“cin” (extraction operator): By using overloaded operator >> with cin stream, C++ handles the
standard input.
int age;
cin>>age;
As shown in the above example, an integer variable ‘age’ is declared and then it waits for cin
(keyboard) to enter the data. “cin” processes the input only when the RETURN key is pressed.
“cout” (insertion operator): This is used in conjunction with the overloaded << operator. It
directs the data that followed it into the cout stream.
Example:
cout<<”Hello, World!”;
cout<<123;
Answer:
However, in case, if we don’t want a function to return any value, we use “void” to indicate that.
This means that we use “void” to indicate that the function has no return value or it returns
“void”.
Example:
void myfunc()
{
Cout<<”Hello,This is my function!!”;
}
int main()
{
myfunc();
return 0;
}
Answer:
Inline function is a function that is compiled by the compiler as the point of calling the function
and the code is substituted at that point. This makes compiling faster. This function is defined by
prefixing the function prototype with the keyword “inline”.
Such functions are advantageous only when the code of the inline function is small and simple.
Although a function is defined as Inline, it is completely compiler dependent to evaluate it as
inline or not.
Answer:
If A is an array then each of its elements is accessed as A[i]. Programmatically, all that is
required for this to work is an iterative block with a loop variable i that serves as an index
(counter) incrementing from 0 to A.length-1.
This is exactly what a loop does and this is the reason why we process arrays using for loops.
Answer:
“delete[]” is used to release the memory allocated to an array which was allocated using new[].
“delete” is used to release one chunk of memory which was allocated using new.
Answer:
A reference variable is an alias name for the existing variable. This means that both the variable
name and the reference variable point to the same memory location. Hence, whenever the
variable is updated, the reference is updated too.
Example:
int a=10;
int& b = a;
Here, b is the reference of a.
Answer:
Storage class determines the life or scope of symbols such as variable or functions.
Answer:
The variable of a constant class object’s member cannot be changed. However, by declaring the
variables as “mutable”, we can change the values of these variables.
Answer:
By default, every local variable of the function is automatic i.e. auto. In the below function both
the variables ‘i’ and ‘j’ are automatic variables.
void f()
{
int i;
auto int j;
}
NOTE: A global variable is not an automatic variable.
A static variable is a local variable that retains its value across the function calls. Static variables
are declared using the keyword “static”. Numeric variables which are static have the default
value as zero.
Answer:
“Register” variable should be used whenever the variable is used. When a variable is declared
with a “register” specifier, then the compiler gives CPU register for its storage to speed up the
lookup of the variable.
Answer:
Answer:
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem.
After creation, the user is not required to know the details of the working of a class.
In general, class acts as a blueprint of a project and can include in various parameters and
functions or actions operating on these parameters. These are called the members of the class.
Q57. Difference between Class and Structure.
Answer:
Structure: In C language, the structure is used to bundle different types of data types together.
The variables inside a structure are called the members of the structure. These members are by
default public and can be accessed by using the structure name followed by a dot operator and
then the member name.
Class: Class is a successor of the Structure. C++ extends the structure definition to include the
functions that operate on its members. By default all the members inside the class are private.
Answer:
Namespace allows us to group a set of global classes, objects and/or functions under a specific
name.
Answer:
Using Declaration is used to refer a name from the namespace without the scope resolution
operator.
Answer:
C++ compiler encodes the parameter types with function/method into a unique name. This
process is called name mangling. The inverse process is called as demangling.
Example:
A::b(int, long) const is mangled as ‘b__C3Ail’.
For a constructor, the method name is left out.
In order to access the class members and put them to use, we should create an instance of a class
which is called an Object. The class has an unlimited lifetime whereas an object has a limited
lifespan only.
Answer:
It is a constructor that accepts one argument of a different type. Conversion constructors are
mainly used for converting from one type to another.
Answer:
A conversion constructor is declared with the explicit keyword. The compiler does not use an
explicit constructor to implement an implied conversion of types. Its purpose is reserved
explicitly for construction.
Q64. What is the role of the Static keyword for a class member variable?
Answer:
The static member variable shares a common memory across all the objects created for the
respective class. We need not refer to the static member variable using an object. However, it can
be accessed using the class name itself.
Answer:
A static member function can access only the static member variable of the class. Same as the
static member variables, a static member function can also be accessed using the class name.
Q66. What’s the order in which the local objects are destructed?
Answer:
Consider following a piece of code:
Class A{
….
};
int main()
{
A a;
A b;
...
}
In the main function, we have two objects created one after the other. They are created in order,
first a then b. But when these objects are deleted or if they go out of the scope, the destructor for
each will be called in the reverse order in which they were constructed.
Hence, the destructor of b will be called first followed by a. Even if we have an array of objects,
they will be destructed in the same way in the reverse order of their creation.
Q67. What is the difference between Method Overloading and Method Overriding in C++?
Answer:
Method overloading is having functions with the same name but different argument lists. This is
a form of compile-time polymorphism.
Method overriding comes into picture when we rewrite the method that is derived from a base
class. Method overriding is used while dealing with run-time polymorphism or virtual functions.
Answer:
sizeof – sizeof operator
. – Dot operator
.* – dereferencing operator
-> – member dereferencing operator
:: – scope resolution operator
?: – conditional operator
Q69. Function can be overloaded based on the parameter which is a value or a reference.
Explain if the statement is true.
Answer:
False. Both, Passing by value and Passing by reference look identical to the caller.
Answer:
By overloading standard operators on a class, we can extend the meaning of these operators, so
that they can also operate on the other user-defined objects.
Function overloading allows us to reduce the complexity of the code and make it more clear and
readable as we can have the same function names with different argument lists.
In terms of C++, inheritance is creating a new class by deriving it from an existing class so that
this new class has the properties of its parent class as well as its own.
Answer:
Inheritance allows code re-usability, thereby saving time on code development.
By inheriting, we make use of a bug-free high-quality software that reduces future problems.
Answer:
Yes.
Answer:
The basic idea behind polymorphism is in many forms. In C++, we have two types of
Polymorphism:
Answer:
A virtual function allows the derived classes to replace the implementation provided by the base
class.
Whenever we have functions with the same name in the base as well as derived class, there arises
an ambiguity when we try to access the child class object using a base class pointer. As we are
using a base class pointer, the function that is called is the base class function with the same
name.
To correct this ambiguity we use the keyword “virtual” before the function prototype in the base
class. In other words, we make this polymorphic function Virtual. By using a Virtual function,
we can remove the ambiguity and we can access all the child class functions correctly using a
base class pointer.
Answer:
A Pure Virtual Member Function is a member function in which the base class forces the derived
classes to override. Normally this member function has no implementation. Pure virtual
functions are equated to zero.
Example:
class Shape { public: virtual void draw() = 0; };
Base class that has a pure virtual function as its member can be termed as an “Abstract class”.
This class cannot be instantiated and it usually acts as a blueprint that has several sub-classes
with further implementation.
Answer:
C++ class does not allow its private and protected members to be accessed outside the class. But
this rule can be violated by making use of the “Friend” function.
As the name itself suggests, friend function is an external function that is a friend of the class.
For friend function to access the private and protected methods of the class, we should have a
prototype of the friend function with the keyword “friend” included inside the class.
Answer:
Friend classes are used when we need to override the rule for private and protected access
specifiers so that two classes can work closely with each other.
Hence, we can have a friend class to be a friend of another class. This way, friend classes can
keep private, inaccessible things in the way they are.
When we have a requirement to access the internal implementation of a class (private member)
without exposing the details by making the public, we go for friend functions.
Answer:
Answer:
In C++ functions are classified as
Return type
Function Name
Parameters
Function body
Answer:
A reference variable is just like a pointer with few differences. It is declared using & Operator.
In other words, reference is another name for an already existing variable.
Answer:
Encapsulation is an object oriented programming concept (oops) which binds together the data
and functions. It is also referred as data hiding mechanism.
Answer :
The types of member functions are
Simple functions
Static functions
Const functions
Inline functions
Friend functions
Q84. Mention what are the decisions making statements in C++? Explain if statement with
an example?
Answer:
The decision making statements in C++ are
if statement
switch statement
conditional operator
Answer:
To run two or more programs simultaneously multi-threading is useful. There are two types of
Answer:
Upcasting is the act of converting a sub class references or pointer into its super class
reference or pointer is called upcasting.
Answer:
Pre-processors are the directives, which give instruction to the compiler to pre-process the
information before actual compilation starts.
Answer:
COPY CONSTRUCTOR is a technique that accepts an object of the same class and copies its
data member to an object on the left part of the assignment.
Answer:
Virtual function is a member function in the base class that you redefine in a derived class. A
virtual function is declared using the virtual keyword. When the function is made virtual, C++
determines which function is to be invoked at the runtime based on the type of the object
pointed by the base class pointer.
Answer:
If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time. One of the important advantages of using an
inline function is that it eliminates the function calling overhead of a traditional function.
Answer: