Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

C++ Interview Questions And Answers For Freshers pdf

C++ Interview Questions and Answers for Freshers pdf

C++ Interview Questions and Answers for Freshers

“C++ Interview Questions and Answers for Freshers”

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.

Click on the button below to know about C++ Language.

C++ Interview questions for freshers pdf

About C++ Language

Few important points to keep in mind:

  • C was a procedural language i.e. it didn’t have the concept of classes and objects.
  • C++ was made to cover this and additional functionalities of Object Oriented Programming were added.
  • C++ features –
    • Object Oriented
    • Procedural
    • Case Sensitive
    • Generic

and more. Click on the button below to know more about C++.

Commonly Asked C++ Interview Questions and Answers for Freshers pdf

1. What are the differences between C and C++?

Solution:-

  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.

2. What is role of static keyword on class member variable?

Solution:-

Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. Static Keyword can be used with following,

  1. Static variable in functions
  2. Static Class Objects
  3. Static member Variable in class
  4. Static Methods in class
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.

3What is the basic structure of a C++ program?

Solution:-

The basic structure of a C++ program is shown below:
#include<headerfile>
int main()
{
cout<<”Hello,World!”;
return 0;
}
  • 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.

 4. What are the advantages of C++?

Solution:-

Some of the main advantages of the C++ programming language are:

  • 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.

5. Explain what are Operators and explain with an example?

Solution:-

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++, 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;
}

It will give the output as 31.

 6. If You Want To Share Several Functions Or Variables In Several Files Maintaining The Consistency How Would You Share It?

Solution:-

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(){

	//This will call overloaded new function from 
	//class Book, not from OS.
	Book *ob = new Book(); 
	delete ob;

	return 0;
}

OUTPUT:

  1. Overloaded new operator
  2. constructor
  3. Destructor
  4. overloaded delete operator

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.

9. What are virtual functions – Write an example?

Solution:-

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"; }
};

class Derived: public Base {
public:
void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}

Output:

In Derived

10. Comment on Assignment Operator in C++.

Solution:-

An assignment operator in C++ is used to assign a value to another variable.

x = 5;

This line of code assigns the integer value 5 to variable a.

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.

11. Define namespace in C++.

Solution:-

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;
}

12. Explain what is C++ exceptional handling?

Solution:-

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.

13.  Define Pointers?

Solution:-

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.

14.What is the output of the following code:

#include 

class A {
public:
    A() {}
    ~A() {
        throw 42;
    }
};

int main(int argc, const char * argv[]) {
    try {
        A a;
        throw 32;
    } catch(int a) {
        std::cout << a;
    }
}

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. 

15. What are the differences between references and pointers?

Solution:-

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. 

References are less powerful than pointers
1) Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
3) A reference must be initialized when declared. There is no such restriction with pointers

References are safer and easier to use:
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location (See questions 5 and 6 in the below exercise )
2) Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also, members of an object reference can be accessed with dot operator (‘.’), unlike pointers where arrow operator (->) is needed to access members.

16.What is the difference between equal to (==) and Assignment Operator (=)?

Solution:-

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.

17. Which operations are permitted on pointers?

Solution:-

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.

There are two types of increment/decrement pointers:

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

18. Mention what are the decision-making statements in C++? Explain if statement with an example?

Solution:-

The major decision making statements in C++ are

  • if statement
  • switch statement
  • conditional operator

For example, we want to implement if condition in C++

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

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    // do something;
}

Solution:-

This code will result in an infinite loop.

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.

21. What is the role of protected access specifier?

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.

22. Mention the storage classes names in C++.

Solution:-

The following are storage classes supported in C++ :

  • 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.

24. Distinguish between shallow copy and deep copy.

Solution:-

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.

25. What is a class template?

Solution:-

A template class is a prototype class. A template class can be described using the keyword template.

IMPORTANT!!

Few Important pages to be checked

Check these pages to know more Technical Questions and prepare well for you Placements.