Here we have mentioned most frequently asked C++ Interview Questions and Answers specially for freshers and experienced.


 

1. Explain what is a class in C++?

Ans:

A class in C++ can be defined as a collection of function and related data under a single name. It is a blueprint of objects. A C++ program can consist of any number of classes.

2. How can you specify a class in C++?

Ans:

By using the keyword class followed by identifier (name of class) you can specify the class in C++.
Inside curly brackets, body of the class is defined. It is terminated by semi-colon in the end.

For example,

class name{
/ / some data
/ / some functions
} ;

3. Explain what is the use of void main () in C++ language?

Ans:

To run the C++ application it involves two steps, the first step is a compilation where conversion of C++ code to object code take place. While second step includes linking, where combining of object code from the programmer and from libraries takes place. This function is operated by main () in C++ language.

4. Explain what is C++ objects?

Ans:

Class gives blueprints for object, so basically an object is created from a class or in other words an object is an instance of a class. The data and functions are bundled together as a self-contained unit called an object. Here, in the example A and B is the Object.
For example,

Class Student
{
Public:
Int rollno;
String name;
} A, B;

5. Explain what are the characteristics of Class Members in C++?

Ans:

• Data and Functions are members in C++,
• Within the class definition, data members and methods must be declared
• Within a class, a member cannot be re-declare
• Other that in the class definition, no member can be added elsewhere

6. Explain what is Member Functions in Classes?

Ans:

The member function regulates the behaviour of the class. It provides a definition for supporting various operations on data held in the form of an object.

7. Define basic type of variable used for a different condition in C++?

Ans:

The variable used for a different condition in C++ are

• Bool: Variable to store boolean values (true or false)
• Char: Variable to store character types
• int : Variable with integral values
• float and double: Types of variables with large and floating point values

8. What is namespace std; and what is consists of?

Ans:

Namespace std; defines your standard C++ library, it consists of classes, objects and functions of the standard C++ library. You can specify the library by using namespace std or std: : throughout the code. Namespace is used to differentiate the same functions in a library by defining the name.

9. Explain what is Loop function? What are different types of Loops?

Ans:

In any programming language, to execute a set of statements repeatedly until a particular condition is satisfied Loop function is used. The loop statement is kept under the curly braces { } referred as Loop body.
In C++ language, three types of loops are used
• While loop
• For loop
• Do-while loop

10. Explain how functions are classified in C++ ?

Ans:

In C++ functions are classified as
• Return type
• Function Name
• Parameters
• Function body



 

11. Explain what are Access specifiers in C++ class? What are the types?

Ans:

Access specifiers determine the access rights for the statements or functions that follow it until the end of class or another specifier is included. Access specifiers decide how the members of the class can be accessed. There are three types of specifiers
• Private
• Public
• Protected

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

Ans:

Operators are specific operands in C++ that is used to perform specific operations to obtain a result. 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 when you run the command

13. What is the C-style character string?

Ans:

The string is actually a one-dimensional array of characters that is terminated by a null character ‘\0’.
For example, to type hello word

#include
Using namespace std;
Int main ()
{
char greeting[6] = { ‘H’ , ‘e’ , ‘l’ ,’l’ , ‘o’ , ‘
#include
Using namespace std;
Int main ()
{
char greeting[6] = { ‘H’ , ‘e’ , ‘l’ ,’l’ , ‘o’ , ‘\0’};
cout << “Greeting message:” ;
cout << greeting << endl;
return 0;
}
’};
cout << “Greeting message:” ;
cout << greeting << endl;
return 0;
}

On executing this code it will give the result like Greeting message: Hello

14. Explain what is a reference variable in C++?

Ans:

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.

15. Explain what is Polymorphism in C++?

Ans:

Polymorphism in C++ is the ability to call different functions by using only one type of the function call. Polymorphism is referred to codes, operations or objects that behave differently in a different context.
For example, the addition function can be used in many contests like
• 5+5 Integer addition
• Medical+Internship The same ( + ) operator can be used with different meaning with strings
• 3.14 + 2.27 The same ( + ) operator can be used for floating point addition

16. Explain what is data abstraction in C++?

Ans:

Data abstraction is a technique to provide essential information to the outside world while hiding the background details. Here in below example you don’t have to understand how cout display the text “Hello guru99” on the user screen and at the same time implementation of cout is free to change
For example,

#include
Using namespace std;

int main ( )
{
Cout << “Hello guru99” <<endl;
return 0 ;
}

17. Explain what is C++ exceptional handling?

Ans:

The problem that arises during execution of a program is referred as exceptional handling. The exceptional handling in C++ is done by three keywords.
• Try: It identifies a block of code for which particular exceptions will be activated
• Catch: The catch keyword indicates the catching of an exception by an exception handler at the place in a program
• Throw: When a problem exists while running the code, the program throws an exception

18. Explain what is data encapsulation in C++?

Ans:

Encapsulation is an object oriented programming concept (oops) which binds together the data and functions. It is also referred as data hiding mechanism.

19. Mention what are the types of Member Functions?

Ans:

The types of member functions are
• Simple functions
• Static functions
• Const functions
• Inline functions
• Friend functions

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

Ans:

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



 

21. Explain what is multi-threading in C++?

Ans:

To run two or more programs simultaneously multi-threading is useful. There are two types of
• Process-based: It handles the concurrent execution of the program
• Thread-based: It deals with the concurrent execution of pieces of the same program

22. Explain what is upcasting in C++?

Ans:

Upcasting is the act of converting a sub class references or pointer into its super class reference or pointer is called upcasting.

23. Explain what is pre-processor in C++?

Ans:

Pre-processors are the directives, which give instruction to the compiler to pre-process the information before actual compilation starts.

24. Explain what is COPY CONSTRUCTOR and what is it used for?

Ans:

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.

25. What is difference between C and C++ ?

Ans:

[This is a usual C or C++ interview question, mostly the first one you will face if you are fresher or appearing for campus interview. When answering this question please make sure you don’t give the text book type explanations, instead give examples from real software scenario. Answer for this interview question can include below points, though its not complete list. This question itself can be a 1day interview !!!]

  1. C++ is Multi-Paradigm ( not pure OOP, supports both procedural and object oriented) while C follows procedural style programming.
  2. In C data security is less, but in C++ you can use modifiers for your class members to make it inaccessible from outside.
  3. C follows top-down approach ( solution is created in step by step manner, like each step is processed into details as we proceed ) but C++ follows a bottom-up approach ( where base elements are established first and are linked to make complex solutions ).
  4. C++ supports function overloading while C does not support it.
  5. C++ allows use of functions in structures, but C does not permit that.
  6. C++ supports reference variables ( two variables can point to same memory location ). C does not support this.
  7. C does not have a built in exception handling framework, though we can emulate it with other mechanism. C++ directly supports exception handling, which makes life of developer easy.

26. What is a class?

Ans:

[Probably this would be the first question for a Java/c++ technical interview for freshers and sometimes for experienced as well. Try to give examples when you answer this question.]
Class defines a datatype, it’s type definition of category of thing(s). But a class actually does not define the data, it just specifies the structure of data. To use them you need to create objects out of the class. Class can be considered as a blueprint of a building, you can not stay inside blueprint of building, you need to construct building(s) out of that plan. You can create any number of buildings from the blueprint, similarly you can create any number of objects from a class.

class Vehicle
{
public:
int numberOfTyres;
double engineCapacity;
void drive(){
// code to drive the car
}
};

27. What is an Object/Instance?

Ans:

Object is the instance of a class, which is concrete. From the above example, we can create instance of class Vehicle as given below Vehicle vehicleObject;
We can have different objects of the class Vehicle, for example we can have Vehicle objects with 2 tyres, 4tyres etc. Similarly different engine capacities as well.

28. What do you mean by C++ access specifiers ?

Ans:

Access specifiers are used to define how the members (functions and variables) can be accessed outside the class. There are three access specifiers defined which are public, private, and protected
private:
Members declared as private are accessible only with in the same class and they cannot be accessed outside the class they are declared.
public:
Members declared as public are accessible from any where.
protected:
Members declared as protected can not be accessed from outside the class except a child class. This access specifier has significance in the context of inheritance.

29. What are the basics concepts of OOP?

Ans:

Encapsulation
Encapsulation is the mechanism by which data and associated operations/methods are bound together and thus hide the data from outside world. It’s also called data hiding. In c++, encapsulation achieved using the access specifiers (private, public and protected). Data members will be declared as private (thus protecting from direct access from outside) and public methods will be provided to access these data. Consider the below class

class Person
{
private:
int age;
public:
int getAge(){
return age;
}
int setAge(int value){
if(value > 0){
age = value;
}
}
};

In the class Person, access to the data field age is protected by declaring it as private and providing public access methods. What would have happened if there was no access methods and the field age was public? Anybody who has a Person object can set an invalid value (negative or very large value) for the age field. So by encapsulation we can preventing direct access from outside, and thus have complete control, protection and integrity of the data.
Data abstraction
Data abstraction refers to hiding the internal implementations and show only the necessary details to the outside world. In C++ data abstraction is implemented using interfaces and abstract classes.

class Stack
{
public:
virtual void push(int)=0;
virtual int pop()=0;
};

class MyStack : public Stack
{
private:
int arrayToHoldData[]; //Holds the data from stack

public:
void push(int) {
// implement push operation using array
}
int pop(){
// implement pop operation using array
}
};

In the above example, the outside world only need to know about the Stack class and its push, pop operations. Internally stack can be implemented using arrays or linked lists or queues or anything that you can think of. This means, as long as the push and pop method performs the operations work as expected, you have the freedom to change the internal implementation with out affecting other applications that use your Stack class.
Inheritance
Inheritance allows one class to inherit properties of another class. In other words, inheritance allows one class to be defined in terms of another class.

class SymmetricShape
{
public:
int getSize()
{
return size;
}
void setSize(int w)
{
size = w;
}
protected:
int size;
};

// Derived class
class Square: public SymmetricShape
{
public:
int getArea()
{
return (size * size);
}
};

In the above example, class Square inherits the properties and methods of class SymmetricShape. Inheritance is the one of the very important concepts in C++/OOP. It helps to modularise the code, improve reusability and reduces tight coupling between components of the system.

30. What is the use of volatile keyword in c++? Give an example.

Ans:

Most of the times compilers will do optimization to the code to speed up the program. For example in the below code,

int a = 10;
while( a == 10){
// Do something
}

compiler may think that value of ‘a’ is not getting changed from the program and replace it with ‘while(true)’, which will result in an infinite loop. In actual scenario the value of ‘a’ may be getting updated from outside of the program.
Volatile keyword is used to tell compiler that the variable declared using volatile may be used from outside the current scope so that compiler wont apply any optimization. This matters only in case of multi-threaded applications.
In the above example if variable ‘a’ was declared using volatile, compiler will not optimize it. In shot, value of the volatile variables will be read from the memory location directly.


 

31. In how many ways we can initialize an int variable in C++?

Ans:

In c++, variables can be initialized in two ways, the traditional C++ initialization using “=” operator and second using the constructor notation.
Traditional C++ initilization
int i = 10;
variable i will get initialized to 10.
Using C++ constructor notation
int i(10);

32. What is implicit conversion/coercion in c++?

Ans:

Implicit conversions are performed when a type (say T) is used in a context where a compatible type (Say F) is expected so that the type T will be promoted to type F.
short a = 2000 + 20;

In the above example, variable a will get automatically promoted from short to int. This is called implicit conversion/coercion in c++.

33. What are C++ inline functions?

Ans:

C++ inline functions are special functions, for which the compiler replaces the function call with body/definition of function. Inline functions makes the program execute faster than the normal functions, since the overhead involved in saving current state to stack on the function call is avoided. By giving developer the control of making a function as inline, he can further optimize the code based on application logic. But actually, it’s the compiler that decides whether to make a function inline or not regardless of it’s declaration. Compiler may choose to make a non inline function inline and vice versa. Declaring a function as inline is in effect a request to the compiler to make it inline, which compiler may ignore. So, please note this point for the interview that, it is upto the compiler to make a function inline or not.

inline int min(int a, int b)
{
return (a < b)? a : b;
}

int main( )
{
cout << “min (20,10): ” << min(20,10) << endl;
cout << “min (0,200): ” << min(0,200) << endl;
cout << “min (100,1010): ” << min(100,1010) << endl;
return 0;
}
If the complier decides to make the function min as inline, then the above code will internally look as if it was written like
int main( )
{
cout << “min (20,10): ” << ((20 < 10)? 20 : 10) << endl;
cout << “min (0,200): ” << ((0 < 200)? 0 : 200) << endl;
cout << “min (100,1010): ” << ((100 < 1010)? 100 : 1010) << endl;
return 0;
}

34. What do you mean by translation unit in c++?

Ans:

We organize our C++ programs into different source files (.cpp, .cxx etc). When you consider a source file, at the preprocessing stage, some extra content may get added to the source code ( for example, the contents of header files included) and some content may get removed ( for example, the part of the code in the #ifdef of #ifndef block which resolve to false/0 based on the symbols defined). This effective content is called a translation unit. In other words, a translation unit consists of
Contents of source file
Plus contents of files included directly or indirectly
Minus source code lines ignored by any conditional pre processing directives ( the lines ignored by #ifdef,#ifndef etc)

35. What do you mean by internal linking and external linking in c++?

Ans:

[This interview question is related to questions on “translation unit” and “storage classes”]
A symbol is said to be linked internally when it can be accessed only from with-in the scope of a single translation unit. By external linking a symbol can be accessed from other translation units as well. This linkage can be controlled by using static and extern keywords.

36. How many storage classes are available in C++?

Ans:

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.
Following storage classes are available in C++
auto
It’s the default storage class for local variables. They can be accessed only from with in the declaration scope. auto variables are allocated at the beginning of enclosing block and deallocated at the end of enclosing block.

void changeValue(void)
{
auto int i = 1 ;
i++;
printf ( "%d ", i ) ;

}
int main()
{
changeValue();
changeValue();
changeValue();
changeValue();
return 0;
}

Output:-
2 2 2 2
In the above example, every time the method changeValue is invoked, memory is allocated for i and de allocated at the end of the method. So it’s output will be same.
register
It’s similar to auto variables. Difference is that register variables might be stored on the processor register instead of RAM, that means the maximum size of register variable should be the size of CPU register ( like 16bit, 32bit or 64bit). This is normally used for frequently accessed variables like counters, to improve performance. But note that, declaring a variable as register does not mean that they will be stored in the register. It depends on the hardware and implementation.

int main()
{
register int i;
int array[10] = {0,1,2,3,4,5,6,7,8,9};

for (i=0;i<10;i++)
{
printf(“%d “, array[i]);
}
return 0;
}

Output:-
0 1 2 3 4 5 6 7 8 9
The variable i might be stored on the CPU register and due to which the access of i in the loop will be faster.
static
A static variable will be kept in existence till the end of the program unlike creating and destroying each time they move into and out of the scope. This helps to maintain their value even if control goes out of the scope. When static is used with global variables, they will have internal linkage, that means it cannot be accessed by other source files. When static is used in case of a class member, it will be shared by all the objects of a class instead of creating separate copies for each object.

void changeValue(void)
{
static int i = 1 ;
i++;
printf ( "%d ", i ) ;

}

int main()
{
changeValue();
changeValue();
changeValue();
changeValue();
return 0;
}

Output:-
2 3 4 5
Since static variable will be kept in existence till the end of program, variable i will retain it’s value across the method invocations.
extern
extern is used to tell compiler that the symbol is defined in another translation unit (or in a way, source files) and not in the current one. Which means the symbol is linked externally. extern symbols have static storage duration, that is accessible through out the life of program. Since no storage is allocated for extern variable as part of declaration, they cannot be initialized while declaring.

int x = 10;
int main( )
{
extern int y ;
printf("x: %d ", x );
printf("y: %d", y);
return 0;
}
int y = 70 ;

Output:-
x: 10 y: 70
extern variable is like global variable, it’s scope is through out the program. It can be defined anywhere in the c++ program.
mutable
mutable storage class can be used only on non static non const data a member of a class. Mutable data member of a class can be modified even is it’s part of an object which is declared as const.

class Test
{
public:
Test(): x(1), y(1) {};
mutable int x;
int y;
};

int main()
{
const Test object;
object.x = 123;
//object.y = 123;
/*
* The above line if uncommented, will create compilation error.
*/
cout<< “X:”<< object.x << “, Y:” << object.y;
return 0;
}

Output:-
X:123, Y:1
In the above example, we are able to change the value of member variable x though it’s part of an object which is declared as const. This is because the variable x is declared as mutable. But if you try to modify the value of member variable y, compiler will throw error.

You can find the summary of c++ storage class specifiers below

C++ Storage Specifier

Storage Location

Scope Of Variable

Life Time

auto

Memory (RAM)

Local

With in function

static

Memory (RAM)

Local

Life time is from when the flow reaches the first declaration to the termination of program.

register

CPU register

Local

With in function

extern

Memory (RAM)

Global

Till the end of main program

37. What is ‘Copy Constructor’ and when it is called?

Ans:

This is a frequent c++ interview question. Copy constructor is a special constructor of a class which is used to create copy of an object. Compiler will give a default copy constructor if you don’t define one. This implicit constructor will copy all the members of source object to target object.
Implicit copy constructors are not recommended, because if the source object contains pointers they will be copied to target object, and it may cause heap corruption when both the objects with pointers referring to the same location does an update to the memory location. In this case its better to define a custom copy constructor and do a deep copy of the object.

class SampleClass{
public:
int* ptr;
SampleClass();
// Copy constructor declaration
SampleClass(SampleClass &obj);
};

SampleClass::SampleClass(){
ptr = new int();
*ptr = 5;
}

// Copy constructor definition
SampleClass::SampleClass(SampleClass &obj){
//create a new object for the pointer
ptr = new int();
// Now manually assign the value
*ptr = *(obj.ptr);
cout<<“Copy constructor…\n”;
}

38. What is realloc() and free()? What is difference between them?

Ans:

void* realloc (void* ptr, size_t size)
This function is used to change the size of memory object pointed by address ptr to the size given by size. If ptr is a null pointer, then realloc will behave like malloc(). If the ptr is an invalid pointer, then defined behaviour may occur depending the implementation. Undefined behaviour may occur if the ptr has previously been deallocated by free(), or dealloc() or ptr do not match a pointer returned by an malloc(), calloc() or realloc().
void free (void* ptr)
This function is used to deallocate a block of memory that was allocated using malloc(), calloc() or realloc(). If ptr is null, this function does not doe anything.

39. What is difference between shallow copy and deep copy? Which is default?

Ans:

When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a dynamically created field in the source object, shallow copy will copy the same pointer to target object. So you will have two objects with fields that are pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the object itself is copied to target. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy. To make it as deep copy, you need to create a custom copy constructor and override assignment operator.

40. What do you mean by persistent and non persistent objects?

Ans:

Objects that can not be serialized are called non persistent objects. [ Usually database objects are not serialized because connection and session will not be existing when you restart the application. ]



 

41. Is it possible to get the source code back from binary file?

Ans:

Technically it is possible to generate the source code from binary. It is called reverse engineering. There are lot of reverse engineering tools available. But, in actual case most of them will not re generate the exact source code back because many information will be lost due to compiler optimization and other interpretations.

42. What are virtual functions and what is its use?

Ans:

Virtual functions are member functions of class which is declared using keyword ‘virtual’. When a base class type reference is initialized using object of sub class type and an overridden method which is declared as virtual is invoked using the base reference, the method in child class object will get invoked.

class Base
{
int a;
public:
Base()
{
a = 1;
}
virtual void method()
{
cout << a;
}
};

class Child: public Base
{
int b;
public:
Child()
{
b = 2;
}
virtual void method()
{
cout << b;
}
};

int main()
{
Base *pBase;
Child oChild;
pBase = &oChild;
pBase->method();
return 0;
}

In the above example even though the method in invoked on Base class reference, method of the child will get invoked since its declared as virtual.

43. What do you mean by pure virtual functions in C++? Give an example?

Ans:

Pure virtual function is a function which doesn’t have an implementation and the same needs to be implemented by the the next immediate non-abstract class. (A class will become an abstract class if there is at-least a single pure virtual function and thus pure virtual functions are used to create interfaces in c++).

44. How to create a pure virtual function?

Ans:

A function is made as pure virtual function by the using a specific signature, ” = 0″ appended to the function declaration as given below,

class SymmetricShape {
public:
// draw() is a pure virtual function.
virtual void draw() = 0;
};

45. Why pure virtual functions are used if they don’t have implementation / When does a pure virtual function become useful?

Ans:

Pure virtual functions are used when it doesn’t make sense to provide definition of a virtual function in the base class or a proper definition does not exists in the context of base class. Consider the above example, class SymmetricShape is used as base class for shapes with symmetric structure(Circle, square, equilateral triangle etc). In this case, there exists no proper definition for function draw() in the base class SymmetricShape instead the child classes of SymmetricShape (Cirlce, Square etc) can implement this method and draw proper shape.

46. What is virtual destructors? Why they are used?

Ans:

Virtual destructors are used for the same purpose as virtual functions. When you remove an object of subclass, which is referenced by a parent class pointer, only destructor of base class will get executed. But if the destructor is defined using virtual keyword, both the destructors [ of parent and sub class ] will get invoked.

47. What you mean by early binding and late binding? How it is related to dynamic binding?

Ans:

Binding is the process of linking actual address of functions or identifiers to their reference. This happens mainly two times.
During compilation : This is called early binding
For all the direct function references compiler will replace the reference with actual address of the method.
At runtime : This is called late binding.
In case of virtual function calls using a Base reference, as in shown in the example of question no: 2, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at runtime.
Dynamic binding is another name for late binding.

48. What is meant by reference variable in C++?

Ans:

In C++, reference variable allows you create an alias (second name) for an already existing variable. A reference variable can be used to access (read/write) the original data. That means, both the variable and reference variable are attached to same memory location. In effect, if you change the value of a variable using reference variable, both will get changed (because both are attached to same memory location).
How to create a reference variable in C++
Appending an ampersand (&) to the end of datatype makes a variable eligible to use as reference variable.

int a = 20;
int& b = a;

The first statement initializes a an integer variable a. Second statement creates an integer reference initialized to variable a
Take a look at the below example to see how reference variables work.

int main ()
{
int a;
int& b = a;

a = 10;
cout << “Value of a : ” << a << endl;
cout << “Value of a reference (b) : ” << b << endl;

b = 20;
cout << “Value of a : ” << a << endl;
cout << “Value of a reference (b) : ” << b << endl;

return 0;
}

Above code creates following output.
Value of a : 10
Value of a reference (b) : 10
Value of a : 20
Value of a reference (b) : 20

49. What are the difference between reference variables and pointers in C++?

Ans:

Pointers

Reference Variables

Pointers can be assigned to NULL

References cannot be assigned NULL. It should always be associated with actual memory, not NULL.

Pointers can be (re)pointed to any object, at any time, any number of times during the execution.

Reference variables should be initialized with an object when they are created and they cannot be reinitialized to refer to another object

Pointer has own memory address and location on stack

Reference variables has location on stack, but shares the same memory location with the object it refer to.

50. What is the full form of OOPS?

Ans:

Object Oriented Programming System.




 

51. What is a class?

Ans:

Class is a blue print which reflects the entities attributes and actions. Technically defining a class is designing an user defined data type.

52. What is an object?

Ans:

An instance of the class is called as object.
List the types of inheritance supported in C++.
Single, Multilevel, Multiple, Hierarchical and Hybrid.

53. What is the role of protected access specifier?

Ans:

If a class member is protected then it is accessible in the inherited class. However, outside the both the private and protected members are not accessible.

54. What is encapsulation?

Ans:

The process of binding the data and the functions acting on the data together in an entity (class) called as encapsulation.

55. What is abstraction?

Ans:

Abstraction refers to hiding the internal implementation and exhibiting only the necessary details.

56. What is inheritance?

Ans:

Inheritance is the process of acquiring the properties of the exiting class into the new class. The existing class is called as base/parent class and the inherited class is called as derived/child class.

57. Explain the purpose of the keyword volatile.

Ans:

Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence avoiding compiler optimization on the variable reference.

58. What is an inline function?

Ans:

A function prefixed with the keyword inline before the function definition is called as inline function. The inline functions are faster in execution when compared to normal functions as the compiler treats inline functions as macros.

59. What is a storage class?

Ans:

Storage class specifies the life or scope of symbols such as variable or functions.

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

Ans:

The following are storage classes supported in C++
auto, static, extern, register and mutable


 

61. What is the role of mutable storage class specifier?

Ans:

A constant class object’s member variable can be altered by declaring it using mutable storage class specifier. Applicable only for non-static and non-constant member variable of the class.

62. Distinguish between shallow copy and deep copy.

Ans:

Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field by field from object to another. Deep copy is achieved using copy constructor and or overloading assignment operator.

63. What is a pure virtual function?

Ans:

A virtual function with no function body and assigned with a value zero is called as pure virtual function.

64. What is an abstract class in C++?

Ans:

A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class.

65. What is a reference variable in C++?

Ans:

A reference variable is an alias name for the existing variable. Which mean both the variable name and reference variable point to the same memory location. Therefore updation on the original variable can be achieved using reference variable too.

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

Ans:

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.

67. Explain the static member function.

Ans:

A static member function can be invoked using the class name as it exits before class objects comes into existence. It can access only static members of the class.

68. Name the data type which can be used to store wide characters in C++.

Ans:

wchar_t

69. What are/is the operator/operators used to access the class members?

Ans:

Dot (.) and Arrow ( -> )

70. Can we initialize a class/structure member variable as soon as the same is defined?

Ans:

No, Defining a class/structure is just a type definition and will not allocated memory for the same.



 

71. What is the data type to store the Boolean value?

Ans:

bool, is the new primitive data type introduced in C++ language.

72. What is function overloading?

Ans:

Defining several functions with the same name with unique list of parameters is called as function overloading.

73. What is operator overloading?

Ans:

Defining a new job for the existing operator w.r.t the class objects is called as operator overloading.

74. Do we have a String primitive data type in C++?

Ans:

No, it’s a class from STL (Standard template library).

75. Name the default standard streams in C++.

Ans:

cin, cout, cerr and clog.

76. Which access specifier/s can help to achive data hiding in C++?

Ans:

Private & Protected.

77. When a class member is defined outside the class, which operator can be used to associate the function definition to a particular class?

Ans:

Scope resolution operator (::)

78. What is a destructor? Can it be overloaded?

Ans:

A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters.

79. What is a constructor?

Ans:

A constructor is the member function of the class which is having the same as the class name and gets executed automatically as soon as the object for the respective class is created.

80. What is a default constructor? Can we provide one for our class?

Ans:

Every class does have a constructor provided by the compiler if the programmer doesn’t provides one and known as default constructor. A programmer provided constructor with no parameters is called as default constructor. In such case compiler doesn’t provides the constructor.




 

81. Which operator can be used in C++ to allocate dynamic memory?

Ans:

‘new’ is the operator can be used for the same.

82. What is the purpose of ‘delete’ operator?

Ans:

‘delete’ operator is used to release the dynamic memory which was created using ‘new’ operator.

83. Can I use malloc() function of C language to allocate dynamic memory in C++?

Ans:

Yes, as C is the subset of C++, we can all the functions of C in C++ too.

84. Can I use ‘delete’ operator to release the memory which was allocated using malloc() function of C language?

Ans:

No, we need to use free() of C language for the same.

85. What is a friend function?

Ans:

A function which is not a member of the class but still can access all the member of the class is called so. To make it happen we need to declare within the required class following the keyword ‘friend’.

86. What is a copy constructor?

Ans:

A copy constructor is the constructor which take same class object reference as the parameter. It gets automatically invoked as soon as the object is initialized with another object of the same class at the time of its creation.

87. Does C++ supports exception handling? If so what are the keywords involved in achieving the same.

Ans:

C++ does supports exception handling. try, catch & throw are keyword used for the same.

88. Explain the pointer – this.

Ans:

This, is the pointer variable of the compiler which always holds the current active object’s address.

89. What is the difference between the keywords struct and class in C++?

Ans:

By default the members of struct are public and by default the members of the class are private.

90. Can we implement all the concepts of OOPS using the keyword struct?

Ans:

Yes.


 

91. What is the block scope variable in C++?

Ans:

A variable whose scope is applicable only within a block is said so. Also a variable in C++ can be declared anywhere within the block.

92. What is the role of the file opening mode ios::trunk?

Ans:

If the file already exists, its content will be truncated before opening the file.

93. What is the scope resolution operator?

Ans:

The scope resolution operator is used to
Resolve the scope of global variables.
To associate function definition to a class if the function is defined outside the class.

94. What is a namespace?

Ans:

A namespace is the logical division of the code which can be used to resolve the name conflict of the identifiers by placing them under different name space.

95. What are command line arguments?

Ans:

The arguments/parameters which are sent to the main() function while executing from the command line/console are called so. All the arguments sent are the strings only.

96. What is a class template?

Ans:

A template class is a generic class. The keyword template can be used to define a class template.

97. How can we catch all kind of exceptions in a single catch block?

Ans:

The catch block with ellipses as follows

catch(…) 
{
}

98. What is keyword auto for?

Ans:

By default every local variable of the function is automatic (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 can’t be an automatic variable.

99. What is a static variable?

Ans:

A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.

void f() 
{
static int i;

++i;
printf(“%d “,i);
}

If a global variable is static then its visibility is limited to the same source code.

100. What is the purpose of extern storage specifier.

Ans:

Used to resolve the scope of global symbol

#include

using namespace std;
main() {
extern int i;

cout<<i<<endl;
}
int i = 20;



 

101. What is the meaning of base address of the array?

Ans:

The starting address of the array is called as the base address of the array.

102. When should we use the register storage specifier?

Ans:

If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable.

103. Can a program be compiled without main() function?

Ans:

Yes, it can be but cannot be executed, as the execution requires main() function definition.

104. Where an automatic variable is stored?

Ans:

Every local variable by default being an auto variable is stored in stack memory

105. What is a container class?

Ans:

A class containing at least one member variable of another class type in it is called so.

106. What is a token?

Ans:

A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol.

107. What is a preprocessor?

Ans:

Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins.

108. What are command line arguments?

Ans:

The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system.

main( int count, char *args[]) {
}

109. What are the different ways of passing parameters to the functions? Which to use when?

Ans:

Call by value – We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used.
Call by address – We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.
Call by reference – The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters.

110. What is reminder for 5.0 % 2?

Ans:

Error, It is invalid that either of the operands for the modulus operator (%) is a real number.




 

111. Which compiler switch to be used for compiling the programs using math library with g++ compiler?

Ans:

Opiton –lm to be used as > g++ –lm

112. Can we resize the allocated memory which was allocated using ‘new’ operator?

Ans:

No, there is no such provision available.

113. Who designed C++ programming language?

Ans:

Bjarne Stroustrup.

114. Which operator can be used to determine the size of a data type/class or variable/object?

Ans:

sizeof

115. How can we refer to the global variable if the local and the global variable names are same?

Ans:

We can apply scope resolution operator (::) to the for the scope of global variable.

116. What are valid operations on pointers?

Ans:

The only two permitted operations on pointers are
Comparision ii) Addition/Substraction (excluding void pointers)

117. What is recursion?

Ans:

Function calling itself is called as recursion.

118. What is the first string in the argument vector w.r.t command line arguments?

Ans:

Program name.

119. What is the maximum length of an identifier?

Ans:

Ideally it is 32 characters and also implementation dependent.

120. What is the default function call method?

Ans:

By default the functions are called by value.


 

121. What are available mode of inheritance to inherit one class from another?

Ans:

Public, private & protected

122. What is the difference between delete and delete[]?

Ans:

Delete[] is used to release the array allocated memory which was allocated using new[] and delete is used to release one chunk of memory which was allocated using new.

123. Does an abstract class in C++ need to hold all pure virtual functions?

Ans:

Not necessarily, a class having at least one pure virtual function is abstract class too.

124. Is it legal to assign a base class object to a derived class pointer?

Ans:

No, it will be error as the compiler fails to do conversion.

125. What happens if an exception is thrown outside a try block?

Ans:

The program shall quit abruptly.

126. Are the exceptions and error same?

Ans:

No, exceptions can be handled whereas program cannot resolve errors.

127. What is function overriding?

Ans:

Defining the functions within the base and derived class with the same signature and name where the base class’s function is virtual.

128. Which function is used to move the stream pointer for the purpose of reading data from stream?

Ans:

seekg()

129. Which function is used to move the stream pointer for the purpose of writing data from stream?

Ans:

seekp()

130. Are class functions taken into consideration as part of the object size?

Ans:

No, only the class member variables determines the size of the respective class object.



 

131. Can we create and empty class? If so what would be the size of such object.

Ans:

We can create an empty class and the object size will be 1.

132. What is ‘std’?

Ans:

Default namespace defined by C++.

133. What is the full form of STL?

Ans:

Standard template library

134. What is ‘cout’?

Ans:

cout is the object of ostream class. The stream ‘cout’ is by default connected to console output device.

135. What is ‘cin’?

Ans:

cin is the object of istream class. The stream ‘cin’ is by default connected to console input device.

136. What is the use of the keyword ‘using’?

Ans:

It is used to specify the namespace being used in.

137. If a pointer declared for a class, which operator can be used to access its class members?

Ans:

Arrow (->) operator can be used for the same

138. What is difference between including the header file with-in angular braces < > and double quotes “ “

Ans:

If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path

139. S++ or S = S+1, which can be recommended to increment the value by 1 and why?

Ans:

S++, as it is single machine instruction (INC) internally.

140. What is the difference between actual and formal parameters?

Ans:

The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters.




 

141. What is the difference between variable declaration and variable definition?

Ans:

Declaration associates type to the variable whereas definition gives the value to the variable.

142. Which key word is used to perform unconditional branching?

Ans:

goto.

143. Is 068 a valid octal number?

Ans:

No, it contains invalid octal digits.

144. What is the purpose of #undef preprocessor?

Ans:

It will be used to undefine an existing macro definition.

145. Can we nest multi line comments in a C++ code?

Ans:

No, we cannot.

146. What is a virtual destructor?

Ans:

A virtual destructor ensures that the objects resources are released in the reverse order of the object being constructed w.r.t inherited object.

147. What is the order of objects destroyed in the memory?

Ans:

The objects are destroyed in the reverse order of their creation.

148. What is a friend class?

Ans:

A class members can gain accessibility over other class member by placing the class declaration prefixed with the keyword ‘friend’ in the destination class.

149. What do you mean by storage classes?

Ans:

Storage class are used to specify the visibility/scope and life time of symbols(functions and variables). That means, storage classes specify where all a variable or function can be accessed and till what time those variables will be available during the execution of program.