C++ Interview Questions and Answers For Freshers PDF - PrepInsta
C++ Interview Questions and Answers For Freshers PDF - PrepInsta
This page will provide you the most common C++ Interview Question and Answer pdf. Before answering the question one
must be aware about C++ Language.
PrepInsta provides you all the updated information about C++ and all the C ++ Interview Questions and Answers for
Freshers. Go through the page in detailed to know more about C ++ Interview Questions and Answers for Freshers pdf.
C++ theory
and more. Click on the button below to know more about C++.
1. C++ can be considered as a superset of C, most C programs except some exceptions, work in C++ and C.
2. C programming is a little bit limited and is a procedural programming language, but C++ supports both procedural and
Object-Oriented programming
3. Since C++ supports object-oriented programming, it is capable of performing tasks like function overloading, templates,
inheritance, virtual functions, friend functions. These features are not present in C.
4. C++ supports exception handling at the language level, in C exception handling is done in the traditional if-else style.
5. C++ supports references, C doesn’t.
6. In C, scanf() and printf() are mainly used input/output. C++ mainly uses streams to perform input and output operations.
cin is a standard input stream and cout is standard output stream.
A static variable does exit though the objects for the respective class are not created. Static member variable share a common
memory across all the objects created for the respective class. A static member variable can be referred using the class name
itself.
3. What is the basic structure of a C++ program?
Solution:-
The first line that begins with “#” is a preprocessor directive. In this case, we are using include as a directive that tells the
compiler to include a header file. The most important header file “iostream.h” which will be used for basic input/output
later in the program.
The next line is the “main” function that returns an integer. The main function is the starting point of execution for any
C++ program. Irrespective of its position in the source code file, the contents of the main function are always executed
first by the C++ compiler.
In the next line, we can see open curly braces that indicate the start of a block of code. After this, we see the
programming instruction or the line of code that uses the count which is the standard output stream (its definition is
present in iostream.h).
This output stream takes a string of characters and prints it to a standard output device. In this case, it is, “Hello, World!”.
Please note that each C++ instruction ends with a semicolon (;), which is very much necessary and omitting it will result in
compilation errors.
Before closing the braces}, we see another line “return 0;”. This is the returning point to the main function.
Every C++ program will have a common basic structure as shown above with a pre-processor directive, main function
declaration followed by a block of code, and then a returning point to the main function which indicates successful execution of
the program.
C++ includes the concept of inheritance. Through inheritance, one can reduce redundancy in the code and can reuse the
existing classes.
Message passing is a technique used for communication between objects.
C++ is a highly portable language means that the software developed using C++ language can run on any platform.
C++ contains a rich function library.
C++ is an object-oriented programming language that includes the concepts such as classes, objects, inheritance,
polymorphism, abstraction.
Data hiding helps the programmer to build secure programs so that the program cannot be attacked by the invaders.
Operators are the basic concept of any programming language, used to build a foundation in programming for freshers.
Operators can be defined as basic symbols that help us work on logical and mathematical operations. Operators in C and C++,
p y p g p p ,
are tools or symbols that are used to perform mathematical operations concerning arithmetic, logical, conditional and, bitwise
operations. The different types of operators available for C++ are Assignment Operator, Compound Assignment Operator,
Arithmetic Operator, Increment Operator, and so on.
For example arithmetic operators, you want to add two values a+b
#include
Using namespace std;
main ()
{
int a= 21 ;
int b= 10 ;
int c;
c= a + b;
cout << "Line 1- Value of c is : " << c << endl ;
return 0;
}
To maintain the consistency between several files firstly place each definition in ‘.c’ file than using external declarations put it in
‘.h’ file after it is included .h file we can use it in several files using #include as it will be in one of the header files, thus to
maintain the consistency we can make our own header file and include it where ever needed.
7. What is the error in the code below and how should it be corrected?
my_struct_t *bar;
/* ... do stuff, including setting bar to point to a defined my_struct_t object ... */
memset(bar, 0, sizeof(bar));
Solution-
sizeof(*bar) should be the last argument of memset instead of sizeof(bar). sizeof(bar) calculates the size of bar (i.e., the
pointer itself) rather than the size of the structure pointed to by bar.
The code can therefore be corrected by using sizeof(*bar) as the last argument in the call to memset.
It might be thought that *bar will cause a dereferencing error if the bar has not been assigned. Therefore an even safer solution
would be to use sizeof(my_struct_t). However, an even sharper candidate must know that in this case using *bar is absolutely
safe within the call to sizeof, even if bar has not been initialized yet since sizeof is a compile-time construct.
8. A C++ class has constructor and overloaded new and delete operator function. If
we create a class object dynamically using new then out of constructor and
overloaded new operator function, which one get called first?
Solution:-
If we have overloaded new operator in the class then on creation of object dynamically, overloaded new operator will be called
first and then class constructor will be called.
And reverse is the case for overloaded delete and destructor i.e. destructor will be called first then overloaded delete operator in
C++ program
Below is the C++ program illustrating overloading of new and delete operators. In this program, we have a class Book and this
class has constructor Book(), overloaded new and delete operator and a destructor ~Book().
On creation of object of Book class in main () function, first overloaded new function will be called then the class constructor.
#include<iostream>
using namespace std;
class Book{
public:
Book(){
cout<<"constructor"<<endl;
}
//Overloaded new operator
void* operator new(size_t size){
cout<<"Overloaded new operator"<<endl;
return malloc(size);
}
//overloaded delete operator
void operator delete(void* ptr){
cout<<"overloaded delete operator"<<endl;
free(ptr);
}
~Book(){
cout<<"Destructor"<<endl;
}
};
int main(){
return 0;
}
OUTPUT:
NOTE:
If we overload new and delete operator in a class, then on creation of object using new, memory will not be directly requested
from operating system, but class new and delete overloaded function will be called in which we write custom memory allocation
or request memory to operating system.
Virtual functions are used with inheritance, they are called according to the type of the object pointed or referred to, not
according to the type of pointer or reference. A virtual function is a member function that is declared within a base class and is
re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base
class, you can call a virtual function for that object and execute the derived class’s version of the function. In other words,
virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual.
Following things are necessary to write a C++ program with runtime polymorphism (use of virtual functions)
1) A base class and a derived class.
2) A function with same name in base class and derived class.
3) A pointer or reference of base class type pointing or referring to an object of derived class.
For example, in the following program bp is a pointer of type Base, but a call to bp->show() calls show() function of Derived
class, because bp points to an object of Derived class.
#include
using namespace std;
class Base {
public:
virtual void show() { cout<<" In Base \n"; }
};
Output:
In Derived
x = 5;
Th t t th l ft f th t i k l al e (l ft l ) d th i ht al e ( i ht l )
The part at the left of the = operator is known as an lvalue (left value) and the right as an rvalue (right value).
The Lvalue must always be a variable whereas the rvalue can be a constant, a variable, the result of an operation, or any
combination of them.
The assignment operation always takes place from the right to left and never at the inverse.
One property which C++ has over the other programming languages is that the assignment operator can be used as
the rvalue (or part of an rvalue) for another assignment.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc)
inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially
when your codebase includes multiple libraries.
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.
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.
The main purpose of using namespace in C++ is to remove the ambiguity. Ambiguity occurs when a different task occurs
with the same name.
For example: if there are two functions that exist with the same name such as add(). In order to prevent this ambiguity,
namespace is used. Functions are declared in different namespaces.
Syntax of namespace:
namespace namespace_name
{
//body of namespace;
}
One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a
program encounters during its execution.
The problem that arises during the execution of a program is referred to as exceptional handling. The exceptional handling in
C++ is done by three keywords.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.
Pointes is a special type of variables that are used to store the memory address of the other variables. Pointers are declared
normally as other variables with a difference of * that is present in front of the pointer identifier. There are two operators that
are used with the pointers one is ‘&’ and another one is ‘*’. & is known as the address of operator and * is known as
dereferencing operator, both are prefix unary operators.
class A {
public:
A() {}
~A() {
throw 42;
}
};
Solution:-
This program will terminate abnormally. throw 32 will start unwinding the stack and destroy class A.
The class A destructor will throw another exception during the exception handling, which will cause the program to crash.
Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with
the * operator to access the memory location it points to.
References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is
also implemented by storing the address of an object.
A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic
indirection, i.e the compiler will apply the * operator for you.
In C++, equal to (==) and assignment operator (=) are two completely different operators.
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.
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.
In C++ programming the following operations are allowed to perform on pointers: Incrementing or decrementing a
pointer: Incrementing a pointer means that we can increment the pointer by the size of a data type to which it points.
1. Pre-increment/decrement pointer: The pre-increment/decrement operator increments the operand by 1, and the value
of the expression becomes the resulting value of the incremented/decremented. Suppose ptr is a pointer then pre-
increment/decrement pointer is represented as ++ptr.
2. Post-increment/decrement pointer: The post-increment/decrement operator increments the operand by 1, but the value
of the expression will be the value of the operand prior to the incremented/decremented value of the operand. Suppose ptr is a
pointer then post-increment/decrement pointer is represented as ptr++.
if statement
switch statement
conditional operator
#include
int main ( )
{
int, x, y;
X= 10;
Y= 5;
if (x > y)
{
Cout << "x is greater than y";
}
}
19. What Is The Difference Between Global Variables And Static Variables?
Solution:-
Global variables are variables which are defined outside the function. The scope of global variables begins at the point where
they are defined and lasts till the end of the file/program. They have external linkage, which means that in other source files,
the same name refers to the same location in memory.
Static global variables are private to the source file where they are defined and do not conflict with other variables in other
source files which would have the same name.
Both global, as well as static variables, have static initialization, which means that if you don’t assign them a value, they will
get initialized to 0 (common variables) or NULL (pointers).
The scope of the variable describes that the variable is accessible at certain point in the program or not.
The difference between global variables and static variables lies in this concept only.
The scope of the global variables remains through out the program also the life span of these variables is through out the
program.
The scope of the static Variables remains within the block of code in which they are created but the life span remains
through out the program.
Thus, the main difference is between the scope of both type of variables.
20.How many times will this loop execute? Explain your answer.
unsigned char half_limit = 150;
Solution:-
Here’s why:
The expression 2 * half_limit will get promoted to an int (based on C++ conversion rules) and will have a value of 300.
However, since i is an unsigned char, it is represented by an 8-bit value which, after reaching 255, will overflow (so it will go
back to 0) and the loop will therefore go on forever.
Solution:-
A class member is accessible in the inherited class if the class member is protected. However, outside both the private and
protected members are not accessible.
auto
static
extern
register
mutable
23. What is the role of a mutable storage class specifier?
Solution:-
The member variable of a constant class object may be used by declaring it with the mutable storage class specifier. Just applies
to the class’s non-static and non-constant member variables.
Shallow copy performs bit-by-bit memory dumping from one object to another. Deep copy is the process of copying an object
field by field from one object to another. The copy function Object() { [native code] } and the overloading assignment operator
are used to achieve deep copy.
A template class is a prototype class. A template class can be described using the keyword template.