C++ interview questions

 Q1. What is the full form of OOPS?

OOPS stands for Object Oriented Programming System.

Q2. What is a class?

A class is a data structure where entities, attributes and actions are clubbed under one name. Class is also considered as a carbon copy which reflects the entities, attributes and actions. In general, a class defines user defined data types. For example, when we say student class, it will have student name, class, age etc. as well as the methods needed for accessing or manipulating with its members.

#include 

class Student{
public:
	char Name[20];
	char Class[15];
	int Age;
	void displayStdName();
	int getAge(char stdName);
}

Q3. What is an object?

An instance of a class is called as object. A class defines the skeleton of the data that we need to represent. Object represents the class with its own values to class members. For example, Student is a class and it will be represented as above. We can create various instance of class, which can have different values at different instance of time.

Student std1, std2;

Here std1 and std2 are two objects of the class Student.

Q4. What is inheritance?

Inheritance is the process of getting the properties of existing class. That means, there will be one existing class, and another additional class will be created which will have properties of existing class as well as its own additional features. Suppose we have three classes – Person, Teacher and Student. Here Person would be a existing class – a base class, Teacher and Student will have the same property as Person, in addition they will have some more features that differentiate them from person or makes them more stronger. It is similar to parent child relationship.

Q5. What is the role of protected access specifier?

Protected data members can be accessed by the class in which it is declared / defined and its derived classes. But these members are not available for any other classes which are not derived class.

Q6. What is encapsulation?

It is the process of combining the data and its functions into one single name is called encapsulation. It is the way we combine all related data and their methods into class. In other words, in a class we can see data members as well as its functions under single name. So it will be easy to get all related data together.

Q7. What is abstraction?

It is the process of hiding all the implementation details from others and providing only the required information to the user. More clearly, when we have to calculate average, there would be two functions – one to calculate the sum and other one to divide the sum by the total number. When user requests for average, he need not know what the sum of the numbers provided is. User will be provided only the function details which actually call average. But he will not be aware of how it has been calculated.

Q8. List the types of inheritance supported in C++.

There are different inheritances supported by C++. Some of them are: Single, Multilevel, Multiple, Hierarchical and Hybrid inheritance.

Q9. Explain the purpose of the keyword volatile.

When we use volatile on the variable, it tells the compiler that it can be changed externally. Therefore compiler will not optimize the code while referencing the variables.

Q10. What is an inline function?

When we prefix a keyword inline before any normal function, the function becomes inline function. These types of functions are considered as macros and they execute faster than the normal functions.

Q11. What is a storage class?

Storage classes are used to indicate the scope of the variables and functions in a program.

Q12. Mention the storage class’s names in C++.

There are 5 types of storage classes: auto, static, extern, register and mutable

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

Member variable of a constant class object can be altered by declaring it using mutable storage class specifier. This is applicable only for non-static and non-constant member variable of the class.

Q14. Distinguish between shallow copy and deep copy?

Shallow copy does memory allocation bit-by-bit from one object to another. Deep copy copies field by field from one object to another object. Deep copy is achieved by using copy constructor and or overloading ‘=’ (assignment operator).

Q15. What is pure virtual function in C++?

It is a virtual function with no function body and assigned with a value zero is known as pure virtual function.

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

Abstract class is the class with at least one pure virtual. One cannot instantiate abstract class. Objects are created out of its derived classes only.

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

This is another name for the variable. Both variable and reference variable will point to the same memory location. Hence changing the value of variable of reference variable will change the variable value.

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

Static keyword is used for class member variables to share the common memory. That means, when objects are created using the class which has static member variable, then all the object’s static member variable will address same memory location. Hence this member variable will have same value in all the objects.

Q19. Explain the static member function.

A static member function can be called using the class name since static member exists before class objects comes into existence. It can access only static members of the class.

Q20. Which data type which can be used to store wide characters in C++?

Wide characters are stored using wchar_t data type.

Q21. What operators are used to access the class members?

Normal class members are accessed using Dot (.) operator and pointer members are accessed using Arrow (->) operator.

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

Defining a class/structure is a type definition which tells which types of variables and functions should be present in the class / structure and will not get any memory for them.

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

Boolean values are represented using bool keyword. This is the primitive data type introduced in C++.

Q24. What is function overloading?

Functions with same name and same list of parameters are called function overloading. It is also defined as function with same signature is called function overloading.

Q25. What is operator overloading?

Defining a new definition for the operator with respect to the class objects is known as operator overloading. For example, ‘+’ operator is used for adding two numbers. But if we use it to merge two numbers (5+8 = 58) then it is an operator overloading.

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

It is a class from Standard template library.

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

There are four default standard streams in C++: cin, cout, cerr and clog.

Q28. Which access specifier/s can help to achieve data hiding in C++?

Private & Protected are the two access specifiers used to achieve data hiding.

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

Scope resolution operator (::) can be used to serve this purpose.

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

A destructor is the member function of the class with same name as the class name and it is prefixed with tilde (~) symbol. It gets executed automatically when the object is no more required in the program. It cannot be overloaded. Its only form is without the parameters.

Q31. What is a constructor?

Constructor is the function within the class with same name as class. It gets executed automatically when class objects are created.

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

Every class contains a constructor provided by its compiler if the programmer doesn’t provide any constructor and known as default constructor. If the programmer writes a constructor with no parameter then that constructor is also called as default constructor if it does not have any parameters. Compiler doesn’t provides the constructor for them.

Q33. Which operator is used in C++ to allocate dynamic memory?

new operator is used for dynamic memory allocation to the objects.

Q34. What is the use of ‘delete’ operator?

delete operator is used to release the memory of the object which is allocated using new operator.

Q35. Can we use malloc () function of C language to dynamically allocate memory in C++?

One can use malloc also to allocate dynamic memory, since C++ supports all the functionalities of C.

Q36. Can we use ‘delete’ operator to de-allocate the memory that is allocated using malloc() function of C language?

delete operator cannot be used to release the memory allocated by malloc () command., One has to use free () to release  the memory allocated by malloc ().

Q37. What is a friend function?

As the name suggests, the function behaves as a friend to a class. Since it is a friend of a class, it can be used to access private and protected members of the class. A friend function is not a member of any class. But it must be programmed in the class definition.

Q38. What is a copy constructor in C++?

A copy constructor is the constructor which takes same class object reference as its parameter. It gets automatically called as soon as the object is initialized with another object of the same class during its creation.

Q39. Does C++ support exception handling? If so what are the keywords involved in exception handling?

C++ does support exception handling. It has try, catch & throw are keyword used for handling the exceptions.

Q40. Explain this pointer?

this, is the pointer variable which always points to the current active object’s address.

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

The main difference between struct and class is: in struct are members are public by default whereas in class, members are private by default.

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

We can implement all the concepts of OOPS using structures.

Q43. What is the block scope variable?

A variable whose scope is valid or active only within a block is said to be block scope variable.

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

If the file already exists, this command truncates the file before opening it.

Q45. What is the scope resolution operator?

The scope resolution operator is used to

  • Determine the scope of global variables.
  • Links the function definition to the class if the function is defined outside the class.

Q46. What is a namespace?

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

Q47. What are command line arguments?

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

Q48. What is a class template?

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

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

Below is the syntax for using catch block to capture all kinds of exceptions.

catch(…)
{
  //code to execute inside catch
}

Q49. What is keyword auto for?

All the local variables are automatic (auto) variable by default. We need not explicitly specify the variable as auto while declaring it. In below example, both ‘I’ and ‘j’ are auto variables. But global variable cannot be auto variable.

void f()
{
	int i;
	auto int j;
}

Q50. What is a static variable?

These are the variable which will share the same memory. Hence its value will not be initialized to zero when any new object is created or function is called. It retains its previous value throughout the program. Its initial value would be zero. Latter it can be incremented or decremented. If a global variable is static then its visibility is limited to the same source code. In below program, the value of i will be automatically initialized to zero as soon as it is declared. It will be incremented subsequently as we call the function. i.e.; If function is called thrice then it will display 1, 2, 3.

#include 
void f()
{
	static int i;

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

Q51. What is the purpose of extern storage specifier?

It is used to resolve the scope of global symbo

#include 
using namespace std;

int i = 20;

void main()
{
	extern int i;
	cout << i << endl;
}

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

Beginning memory address of the array is called base address of the array. It is the address of array with index zero, say &A[0].

Q53. When should we use the register storage specifier?

If a variable is used most frequently, then retrieving such variable from memory needs frequent access. Therefore it should be declared using register storage specifier, so that the compiler gives CPU register for its storage which speeds up the variable retrieval.

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

A program can be compiled without main program. But it should have main() function to execute the program.

Q55. Where an automatic variable is stored?

Every automatic variable are stored in stack memory. Even local variables are found in stack memory.

Q56. What is a container class?

A class with at least one member variable of another class type in it is called container class. In other words, a container class is the one which contains at least one object of another class as its member variable.

Q57. What is a token?

A token can be a keyword, an identifier, a constant, a string literal, or a symbol that are used in the program.

Q58. What is a preprocessor?

Preprocessor is a directive which directs the compiler to perform certain functions before compiling the actual code.

Q59. What are command line arguments?

In a general program, the user will be prompted to enter the data values when it executes. As the program goes on compiling and finds the request for any input, it prompts the user for their input. But in a command line program, while we enter the execute command itself, we need to input the values that are required in the program. Program will take the values entered as and when required. It will not prompt the user to enter the values while running the program.

This is achieved by passing the arguments to the main () function like below. It will have two parameters passed: first one is total number of arguments that are passed as the command line arguments. Second one is the array which will have the actual values that are used in the program for some operation. This can be any array with size equal to first argument. The second argument is always an array of character pointers.

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

}

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

  • Call by value: In this method, only the values are passed to the function as arguments. In this case, the values passed will be manipulated within the program, but its actual value in the variable will not be modified.
  • Call by address: Here address of the actual parameters is passed instead of values. One can opt for this method if one needs to modify both actual parameters and formal parameters.
  • Call by reference: The actual parameters are receives new reference variables as formal parameters. One can opt this method if they want both actual parameters and formal parameters to be modified.

 

61. What is reminder for 5.0 % 2?

It is an error as operand is a real number. Modulus function works only on integer values.

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

Opiton –lm is used as compiler switch for compiling programs with math library.

 g++ –lm

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

This operator does not allow to resize the allocated memory using ‘new’ operator. This operator is used for allocating new memory to the objects.

64. Who designed C++ programming language?

Bjarne Stroustrup designed C++ programming language.

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

sizeof is used to find the size of the variable or object.

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

Scope resolution operator (::) is used to refer the global variables in the program.

67. What are valid operations on pointers?

The valid operations on pointers are

  • Comparison of two pointers
  •  Addition/Subtraction of two pointers (excluding void pointers)

68. What is recursion?

Function calling the same is called as recursion.

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

First string in the command line argument is the name of the program.

70. What is the maximum length of an identifier?

In general it is 32 characters. But it varies depending on the machine.

71. What is the default function call method?

The functions are called by value by default.

72. What are available modes of inheritance to inherit one class from another?

Modes of inheritance are: Public, private & protected

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

delete will release the memory allocated to single object whereas delete [] will release the memory allocated to array of objects (all the memory assigned to the array of objects will be  released).

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

In order to a class to be abstract, at least one member function has to be pure virtual function.

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

It is not legal to assign base class object to a derived class pointer. The compiler will fail to do this, and throw an error.

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

The program will end abruptly.

77. Are the exceptions and error same?

They are not same. Exceptions are the errors or defects in the program that can be handled using try..catch blocks. Errors are also defects in the program that cannot be handled, but needs to be debugged.

78. What is function overriding?

If a function is declared in base class as virtual and is defined in the derived class with same name and signature, then it is called as function overriding.

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

Seekg () is used for this purpose.

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

Seekp () is used for this purpose.

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

Only the class members (variables) are considered to calculate the object size.

82. Can we create and empty class? What would be the size of such object.

Yes, we can create an empty class. Size of the object of the empty class will be one.

83. What is ‘std’?

It is the default namespace defined by C++.

84. What is ‘cout’?

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

85. What is ‘cin’?

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

86. What is the use of the keyword ‘using’ in C++?

The ‘using’ keyword is used before the namespace and is used for indicate the compiler that which namespace has to be used for the current code.

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

Arrow (->) operator can be used for accessing  pointer member of the class.

88. What is difference between including the header file with-in angular and double quotes ?

If a header file is included with in angular bracket (<>) then the compiler searches for that header file only with in the built in include path. If a header file is included with in double quotes then the compiler searches for that header file first in the current working directory, if not found then it will search in the built in include path. This is because the header files within <> are built in header files where as the ones within the “” are user defined files.

89. S++ or S=S+1, which can be recommended to increment the value by 1? Why?

S++, is single machine instruction (INC) internally. Hence it will be faster than S=S+1.

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

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

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

When we declare a variable, the compiler will get know about its data type, whereas variable definition tells the value to the variable.

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

goto keyword is used for unconditional branching in the program.

93. Is 068 a valid octal number?

No, since it has 8, it is an invalid octal number.

94. What is the purpose of #undef preprocessor?

It is used to undefine the macro definition that is already defined.

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

No, C++ does not support nesting a multiline comment.

96. What is a virtual destructor?

A virtual destructor guarantees that the objects are released in the reverse order of the object being constructed with respect to their inheritance.

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

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

98. What is a friend class?

A class is said to be friend class of another class, if the class members of one class can be accessed by another class. In other words, when two classes are not inherited or derived, and if we want to access the members of one class in another class, then we make one of the class friend to another. This is achieved by prefixing ‘friend’ keyword while declaring it.

Function Overloading

99. Does C support Function Overloading like C++?

No, C does not support function overloading like C++. For example, consider the function printf. It takes various types of input like characters, string, integer, float, double etc. and prints the output on the screen. This may look like function overloading. But passing different argument list to the function is not a function overloading. Hence C does not support any function overloading.

How to Read Complex C Declarations

100. What is a Rule for Reading Complex C/C++ Declarations

C/C++ declarations are usually composed of data types, pointers, arrays, functions, structures etc. Hence when we see any C/C++ declaration we will be confused to interpret what it is actually meant. Therefore we have some set of rules which tells us how to read these declarations to understand them. The basic rule for reading C/C++ declaration is:

  • Always start saying the statement from the variable name or identifier. For example, if we find a declaration as ‘intintVar;’ we will start saying ‘intVar is a….’.
  • Look right of the variable name. If there is a right parenthesis stop there, else continue reading the right of the variable name. i.e.; in declaration ‘int *(intVar [10]);’, we get variable name first, then we look right till we get the right parenthesis. So we get array of 10 elements. Hence our statement becomes‘intVar is an array of 10 elements’. Suppose we did not have any array to the right but simply right parenthesis. Then we will stop there itself and our statement will remain as ‘intVar is a….’.
  • Start reading left till left parenthesis. That means, once the right parenthesis is reached, start reading the things left to the variable name. In declaration ‘int *(intVar [10]);’, we have only left parenthesis here. Hence stop. Suppose we have declaration like in declaration ‘int (*intVar [10]);’, then our statement will become ‘intVar is an array of 10 pointer elements’. In other words, once variable nameis read, read all the things right of the variable and then left of the variable within the parenthesis.
  • Once all the things within parenthesis are read, jump out of it, and start reading right and then left. Repeat this till the end. Therefore, in declaration ‘int *(intVar [10]);’, we have finished reading within brackets. Hence jump out of it to read right. But there is nothing. Hence look at left of it, where we see pointer. Hence our statement becomes ‘intVar is an array of 10 elements of pointers’. Now again see the right; nothing is present. Look at left and we see ‘int’. Hence the statement becomes ‘intVar is an array of 10 elements of integer pointers.

This is how we have to read the declarations to understand what could be stored in those variables.

101. Given the following complex C declarations, what does each one mean?

  • int (*p)[ 5 ];  

As a rule, we have to start from variable name, i.e.; ‘p’ – ‘p is a ‘. Next move to the right of it till right parenthesis – we get close bracket. Hence jump to left of the variable name till left parenthesis. We have pointer and left parenthesis. Therefore our statement becomes ‘p is a pointer’. Once reading right and left of the variable within the parenthesis is complete, jump out of it and read right. We have array of 5 elements. Hence the statement becomes ‘p is a pointer to an array of 5 elements’. Since right is complete, read left where we have datatype ‘int’. Hence the final statement becomes ‘p is a pointer to an array of 5 integer elements’.

  • char *x[ 3 ][ 4 ];

Let us start from variable name ‘x’. Let us move to the right of it. We have 2-dimensional array. That means, ‘x is an array of 3X4 size’. A 2D array can also be said to be an array of array of size N, i.e.; an array of 3 arrays of size 4. Now read the left of it – a pointer. That means, ‘x is an array of 3 arrays of size 4 pointers’. Now there is nothing to the right of it. Hence in the left we have its datatype. Therefore our final statement becomes ‘x is an array of 3 arrays of size 4 pointers of type char’.

  • int *(*a[ 10 ])();

Like we saw in above examples, let us start from ‘a’ – ‘a is a ‘. Going to right of it, we get array of size 10 and left of it we get a pointer. Hence our statement becomes ‘a is an array 10 pointer elements’. Since we have finished reading within brackets, jump out of it. We have open and close bracket indicating that it is a function. Hence statement becomes ‘a is an array 10 pointers to functions’. No proceed to left, where we have pointer and a datatype, indicating ‘a’ is an array 10 pointers to functions returning integer pointer’.

  • int (*t[])();

Now this is much simpler for us. It will be ‘t is an array of pointers to function returning integer value’. This is evaluated using the rules – starting from t, right to it an array, left to it a pointer, right to it a function and left to it a returning datatype.

C++ abstract keyword

102. Does C++ have a keyword for “abstract” ?

C++ does not support abstract classes by using ‘abstract’ keyword. But the same functionality is implemented by using pure virtual function. In other words, a pure virtual function is the one which does not have any implementation. Hence any class containing pure virtual function cannot have any object, which is similar to an abstract class. A abstract class is the one which cannot have any object but it can have derived classes from which objects can be created. Hence we use the concept of pure virtual function to create abstract class in C++. At least one pure virtual function within a class makes that class abstract and no objects can be created using it. We will have to create child classes to implement pure virtual function and from which objects can also be created.

103. A C++ class is abstract if it has a pure virtual function

The concept of pure virtual function is that it is not implemented within the class in which it is declared. Hence we cannot create any objects using the class in which pure virtual function is declared. This concept is similar to abstract class where objects cannot be created from it. Hence C++ has removed “abstract” keyword and uses pure virtual function concept to create abstract classes too.

104. How are abstract classes in C++ different from abstract classes in Java?

In C++, there is no keyword called ‘abstract’. But this does not mean that we cannot create abstract class in C++. In order to create abstract class in C++, we have to use at least one pure virtual function within the class. This will make the class abstract implicitly. We cannot explicitly make the class abstract by specifying ‘abstract’ in C++.

In below class, we have one pure virtual function which makes abstExample class an abstract class.

In Java, we need to explicitly specify ‘abstract’, if a class is abstract. This abstract class may or may not have abstract methods (functions). If we have at least one abstract method within the class, then we have to make that class also abstract. Therefore in Java, abstract class may or may not have abstract method, but ‘abstract’ keyword must be specified before the class name.

105. Are abstract methods the same thing as pure virtual functions?

Both abstract method and pure virtual functions are same. In both, their implementation should be defined in their derived classes. Otherwise their derived class will also become abstract class. In general, we will not have any implementations of abstract method or pure virtual functions in their base class. But in C++, pure virtual functions can have implementations in base class itself.

Pure Virtual Function

106. What is a pure virtual function?

A virtual function which does not have any body or definition is called pure virtual function. In order to indicate that virtual function is pure, we use ‘=0’ after the virtual function declaration. This indicates that the function does not have any body or definition. A class with pure virtual function cannot be instantiated to have objects. It should have derived classes where this pure virtual function has to be implemented so that objects can be created from this derived class.

107. What is pure specifier?

In C++, there is no keyword to specify that the virtual function is a pure virtual function. Instead, we use ‘=0’ after the function declaration to indicate that it is a pure virtual function. Hence ‘=0’ is called as pure specifier. But it does not mean that function is assigned value as zero. It is the indication that function is pure virtual function and function does not have any body or definition.

108. Can a pure virtual function have an implementation?

According to the definition of pure virtual function, it does not have any implementations within the base class, but it can have definition in its derived classes. But in C++, pure virtual function can have implementation in its base class itself. It is completely legal and error free.

#include

classAbstractClassExample{
public:	virtualvoidpure_virtual_func() = 0;  // a pure virtual function
	// note that there is no function body	
};

voidAbstractClassExample::pure_virtual_func() {// implementation of pure virtual function
	int a=10, b=20;
	int result = a + b;
}

109. Why would you want a pure virtual function to have an implementation?

In real world requirements, pure virtual functions will not have implementations in the base class. But some of the requirements where derived class calls the pure virtual function can have some implementations in its base class. Since base class can have implementation for pure virtual function, it is completely legal and valid.

In below example, we can see that derived class calls the pure virtual function pure_virtual_func within it. Hence we have its definition implemented in derived class itself.

classAbstractClassExample {
public:	virtualvoidpure_virtual_func() = 0;  // a pure virtual function
		// note that there is no function body	
};

voidAbstractClassExample::pure_virtual_func() {// implementation of pure virtual function
	int a = 10, b = 20;
	int result;
             result = a + b;
}

classDerivedAbstractClass : publicAbstractClassExample {//derived class
		virtualvoidpure_virtual(); // calls pure virtual function
};

In addition, here the pure virtual function is ‘public’. Hence the call to it in derived class is valid. If it was protected, then also call to this pure virtual function would be valid. If it was private, even though it was implemented in the base class, we will not be able to call the function in the derived class.

110. Can a Pure virtual functions have a definition inside the function declaration?

As per the definition of pure virtual function, it cannot have any definition while declaring. For the same reason, we use ‘=0’ after its declaration to indicate that it does not have any body or definition, and to tell that it is a pure virtual function. Therefore it cannot have definition inside function declaration.
However it is valid in Microsoft visual C++. It allows pure virtual function to have its definition while declaring itself. It considers such implementation as inline definition and makes it valid.

classAbstractClassExample {
public:	virtualvoidpure_virtual_func() = 0{// a pure virtual function
	cout<<"This is valid in MS VC++"<<endl; //pure virtual functionDefinition
};  
};

111. When should pure virtual functions be used in C++?

As we have seen above, a pure virtual function is the one which will not have any body or definition in the base class. (it can have implementation in the base class but it is not frequently used and not part of the pure virtual function definition). Therefore when we say pure virtual function, we see only the place holder within the base class. This function needs to be defined in the derived classes so that it can have actual meaning as well as derived class to be non-abstract.
Therefore main use of this function is seen where we need not define them in base class but they will get the meaning in their derived classes. In below example, ArithmeticOperationis a base class and is abstract because of the pure virtual function – operations. The derived classes Addition and Subtract have different implementations for Operations. Here we can understand we have not defined the function operations in the base class and made it as pure virtual function. In the derived class its definition varies depending on the functionalities of the derived class.

classArithmeticOperation { // base class
public:	virtualint operations(int a, int b) = 0;
};

classAddition :ArithmeticOperation{ // derived class
	virtualint operations(inta, intb){
		returna + b;
	}
};

classSubtract :ArithmeticOperation{ // derived class
	virtualint operations(inta, intb){
		returna - b;
	}
};

Lvalues and Rvalues in C

112. What is the difference between rvalues and lvalues?

Any expression consists of some arithmetic or logical operations performed on one or more variables and the result assigned to same or some other variable. Therefore in an expression we have ‘=’ to calculate the value and assign the result. In order to differentiate which calculates the results and which get assigned with result, we use the term lvalue and rvalue. Here lvalue represents the left side of the ‘=’ sign and rvalue represents the right side of the ‘=’ (assignment) sign. Therefore in an expression lvalue variable can be modified and rvalue variables participate in the expression but their values remain unchanged.

Here both lvalue and rvalue have variables which are actually objects in C++. When we say objects, they are actually some place holders in the memory which need not be modified. In terms of expressions, lvalues can be modified if it appears on the left side of the assignment operator. That means lvalue is a modifiable object in the memory. But lvalue also represents const-qualified type which does not appear on the left side of assignment operator. These types of lvalue cannot be modified.Hence we use ‘const-qualified’ type of lvalue for non-modifiable lvalues and ‘modifiable lvalue’ for those lvalues that is present on the LHS of assignment operator.

A=B+C; // A is a ‘modifiable lvalue’
100; //const-qualified lvalue

Rvalue is the one which also occupies place in memory but its value cannot be modified in the current expression. They appear on RHS of assignment operator and can be constant value or expression.

A=B+C; // B+C is a rvalue

113. Suppose we have the example code shown below in C. Will it compile? How do the concepts of lvalues and rvalues work in this problem?

#defineX 8
int main(void)
{
	++X; // will this line compile?
	return 0;
}

In above code, X is a macro defined as a constant 8. Since it is a macro, when it is used in the code or expression, it will be directly replaced by its value. Therefore when we use X as ‘++X’, the compiler will see it as ‘++8’. For any prefix or postfix operator (++, or --), the operand must be a modifiable lvalue. This is because, when increment or decrement operator is used on the operand, it increments or decrements the value and assigns the results to the operand itself. But here X is a macro and it is not modifiable. Therefore when we say ++X, it considers it as ++8. That means 8 should be incremented by one and result, 9 should be assigned to 8(note it will not be assigned to X, since X is a macro and only its value will be used in the expression). This is not possible. Hence it will show an error while compiling.

Below screenshot shows the error message with same code.

Suppose X is not a macro. Then it will compile without any error, because X will then be considered as variable which can become a modifiable lvalue.

Inline vs. Macro

114. In C++, what’s the difference between an inline function and a macro?

The main difference between macros and inline functions is that macros are parsed by preprocessor and inline functions are parsed by compilers. Because of this it creates other differences between them. Since macros are parsed by preprocessors, the definition texts of macros are directly replaced in the code wherever macros appear. In the case of inline function, the whole compiled copy of the function will be replaced in the code whenever function call appears. Therefore in both the cases, it increases the code length by replacing their texts.

Since there is text replacement in both macros and inline functions, there is no overhead to keep track of calling function or code, and called function and their results. This feature of macros and inline functions make them to be used more frequently than functions. But these macros and inline functions will be efficient when we have comparatively smaller requirement to perform within it.

Apart from all these, inline functions are more bugs free than macros. Since macros are parsed by preprocessor, the macro text will be replaced as it is. This will result in wrong results when we are expecting correct result. Next two subsequent questions discuss about the bugs injected by macros and how to get rid of it by using inline functions.

115. Predict the result of following code with macro?

#defineDOUBLE(X) X*X

int y = 3;
int j = DOUBLE(++y);

Here DOUBLE(X) is a macro which is used to find the square of the number passed to it. In the code we assign value 3 to y and pass it as ‘++y’ to the macro, expecting it will increment 3 to 4 and then calculate square of 4, resulting 16. But this is not the case here. As we know already macro will replace the value passed to it as it is. That means the code will look like below when we call macro.

One may wonder how it happened! Since macro is pure text replacement concept, when we pass ++y to it, it will not evaluate ++y to 4. It will directly substitute the values in its expression as ‘++y * ++y’. As we know increment operators have precedence over multiplication, it will evaluate ++y at both the places first. Hence it becomes 4*5 resulting 20.

Therefore in macros, we need to be very careful using the operators and expression. We need to remember that it is always text replacement and parsed by preprocessor. If we had used inline function here, then it will result in 16, which is correct. This is because, it will first evaluate the value passed to it and then replace the code at ‘int j = ….’. Therefore function will calculate ‘4*4=16’.

inlineint DOUBLE(intX){
	returnX*X;
}
int main(){
	int y = 3;
	int j = DOUBLE(++y);
}

 116. What is the result of below code with macro?

#defineADD_TWO(x,y) x += 2; y +=2

bool flag = true;
int j = 5, k = 7;

if (flag)
         ADD_TWO(j, k);

 This is also similar to above problem because we have used macro. Here in macro we have two expressions – one for x and one for y. But we have used macro within the ‘If’ statement. What ‘if’ statement does is, it always binds only the first expression in the macro to it and pushes the rest of the statements out of it. That means it evaluates above code as below:

//should have evaluated like below

if (flag){
          x += 2; 
          y +=2;
}

 

//but it evaluates as below

if (flag){
          x += 2; 
}
y +=2;

That means, y expression will be evaluated irrespective of flag, which is not expected. We need to evaluate both x and y for flag value. But it is not possible using macro. We have to use inline function to do this, where whole compiled function will be replaced to get the result.

inlinevoid ADD_TWO(intx, inty){
	x += 2; 
	y += 2;
}

int main(){
	bool flag = true;
	int j = 5, k = 7;

	if (flag)
		ADD_TWO(j, k);
}

 Diamond Problem

117.  In C++, what’s the diamond problem?

Suppose we have a base class, A. let this A has 2derived classes – B and C. let D be the derived class from both B and C. That means both B and C will have all the features of A. The class D will have all the features of B, which in turn will get the features of A and all the features of C which in turn again will get features of A. When we draw these hierarchies in a diagram it will look like a diamond.

So far the hierarchy looks good and correct. The problem arises when derived class D calls the function or access the variable that is present in A. Since D is derived from B and C and which is derived from A, the D has access to all the variables and functions of A (provided they are public or protected). But what is the problem here in D accessing elements of A? Since D’s immediate parents are B and C, it gets access to A from B and C. That means, both B and C are derived from A, have access to A and have copies of A’s data members. Therefore D should access A’s data members using either B or C. But we cannot specify which parent has to be accessed for this. This will create ambiguity to the compiler in selecting the parent class. This is called diamond problem in C++.

To understand this problem with the help of real life example, consider the classes parent, father, mother and child.  Let Parent class have a function getChild (). If the Child class object tries to access this function, then it will throw an error saying getChild function is ambiguous.

118. Solution to the Diamond Problem or how can it be avoided?

Diamond problem has risen because D is derived from B and C which is in turn derived from A. Therefore D gets two objects of A from B and C. This confuses D while accessing the data members of A – from which class object to access A – whether through B or C. therefore if we make sure only one object of A is created in D, then D will not be confused to access data members of A. This can be done by making inheritance of A as virtual in both B and C. By making this, data object of A will not be created in B and C. Rather A’s object can be created only in D. Hence D will not have to worry about access A’s data members via B or C.

How Vtables Work

119.    What are the different names of vtable?

Vtable is also known as virtual function table, virtual method table and dispatch table.

120.    In C++, what’s a vtable and how does it work?

Like its name suggests, it is a virtual table – which does not exists for developers. That means, it is internal to the C++ code. It is very much essential to handle the polymorphism. Like its alternative names suggests, it’s a virtual function table – that means, it is a table used to maintain the virtual function calls. This is all high level information about vtable. Let us try to understand vtable with the help of an example. Let us consider Shape class and its derived class like below.

#include

classShape{ //base class
	// private members of Shape
public:
	int height;
	int breadth;

	Shape(){ //constructor
		cout<< “Shape Constructor”;
	}
	virtual ~Shape(){ //destructor
		cout<< “ Shape Destructor”;
	}

	virtualvoidgetArea(){}; //virtual function in the base class
};
classSquare : publicShape{ //derived class
public:
	Square(){
		cout<<"Square Constructor";
	}
	~Square(){ //destructor
		cout<<" Square Destructor";
	}
	voidgetArea(){ //overriding the virtual function in the derived class
		cout<<" Area of the Square is"<<(height * breadth);
	};
};

void main(){
	Squaresq = newSquare(); //creates Square object sq
	Shape *shp = &sq; //makes shape pointer shp to point to derived object sq

	shp->getArea(); // calls getArea of Square 
}

In the program above, Shape is the base class and Square is the derived class. The function ‘getArea’ is the virtual function in Shape class and is overridden in Square class. In the main function, we have created derived class object ‘sq’. We have created base class object and made it to point to derived class object ‘sq’. That means, even though shp is base class object, it is pointing to derived class.

In the next step we are calling ‘getArea’ using shp object. Now the question is which function it has to call – base class or derived class? Since it is pointing to derived class, the derived class’s function has to be called. But how the compiler will know which function to be called?

This is handled by vtable. Whenever there is a virtual function in the class, a vtable is maintained to handle it. Since it is a virtual function, it will be overridden in its subsequent derived classes. Therefore, vtable will maintain the pointers to the functions that are overridden. In other words, whenever there is virtual function, vtables will be created for each class. Their respective objects will share their class’ vtables. Each vtable will have pointer to the virtual function or its overridden functions (normal functions will not have vtables). These pointers are known as vpointers.

Therefore at runtime, what happens is, it creates two vtables for shape and square. In above program, when square object sq is created, the program internally creates one vtable, say vt1. When we create base class object shp, it creates another vtable vt2. But this object is made to point to square object. Here vt1 will have pointer to derived class function ‘getArea’ whereas vt2 will pointer to base class function ‘getArea’. Since shp is pointing to derived class object, the vpointer of shp is made to point to vt1, which is derived class function.Therefore when we call shp->getArea();, the program internally replaces the code as shp->vt1->getArea();. That means, the code will direct the compiler to use derive class function. This is how compiler comes to know which function to be accessed.

Virtual Destructors

121. In C++, what’s a virtual destructor and when is it needed?

We use a destructor in a program to deallocate the memory allocated to its objects. When we use destructor to deallocate the memory, it will cleanup all its data members and then deletes that object itself.

Consider below example of shape where Shape is the base class and Square is the derived class.  Both base and derived class has constructor and destructor. In the main function we create a Square object shp, using base class. Since we create derived class, the pointer jumps to create base class constructor first and then creates derived class constructor (this is the rule for creating constructor for derived classes). Then we call delete to deallocate object shp. Even though shp is a derived class object, it is created using base class. Hence it jumps to base class destructor to deallocate the memory. But the rule for deallocating is reverse of allocation – destroy derived class object first and then its base class. Here it first deallocates base class first which is the end of deallocation. Hence it does not deallocate derived class object memory. That means, there is a memory leak for derived class object.

#include

classShape{ //base class
	// private members of Shape
	int height;
	int breadth;

public: 
Shape(){ //constructor
	cout<<“Shape Constructor”;
}
	~Shape(){ //destructor
	cout<<“ Shape Destructor”;
	}
};
classSquare : publicShape{ //derived class
public:
	Square(){
		cout<<"Square Constructor";
	}
	~Square(){ //destructor
		cout<<" Square Destructor";
	}
};

void main(){
	Shape *shp = newSquare(); //creates Square object shp

	deleteshp; // calls destructor
}

Therefore, though the program and class looks correct, it is not able to deallocate the memory properly for derived classes. In order to release all the memory properly, we need to make the base class to call the derived class destructor first. This can be made by making base class destructor as ‘virtual’. Whenever there is a function with ‘virtual’, it jumps to the derived class to find its definition and execute it. Therefore in the above program, let us make base class Shape’s destructor virtual. This will delete the memory of derived class first and then it will come back to base class to delete its memory. Thus, the memory will be deallocated properly and fully.

#include

classShape{ //base class
	// private members of Shape
	int height;
	int breadth;

public: 
Shape(){ //constructor
	cout<<“Shape Constructor”;
}
	virtual~Shape(){ //destructor
	cout<<“ Shape Destructor”;
	}
};
classSquare : publicShape{ //derived class
public:
	Square(){
		cout<<"Square Constructor";
	}
	~Square(){ //destructor
		cout<<" Square Destructor";
	}
};

void main(){
	Shape *shp = newSquare(); //creates Square object shp

	deleteshp; // calls destructor
}

This is what and why a virtual destructor is. Whenever we have one or more virtual function in the base class, then we need to have virtual destructor in the base class. That means, when we have virtual functions in the base class, its definition will definitely be in derived class. Hence when we delete the objects, we need to delete derived class object first than base class. For this to happen we need to have virtual destructor for sure (like we saw in above example).

Friend Classes in C++

122. What is a friend class?

In a class, data members (variables and functions) can be private, public or protected. When a data member is private, it cannot be accessed by any other class or derived class. Such data members are accesses only by those class objects in which it is being declared. If we declare class as ‘friend’ then, we can access the private data members of that class from other classes too. Such class is known as friend class. This friend class also allows ‘protected’ members to be accessed from other class.

123. What are the benefits of a friend class?

Friend class is useful when we have two independent classes have to access the data members of each other. For example, consider one class is linked list array class. It will have all the details about linked list data. Suppose we have another class to maintain the iteration of linked list array in the first class. Now both these classes are independent but needs to have access to iteration class to traverse through linked list array. Therefore it is worth making iteration class as ‘friend’, so that linked list array class can access the iteration.

124. How do you call C functions from C++ ?

Calling its own function in any programming language is simple. Here the question is to call C function from a C++ program. That means, we need to make compiler understand that the function being called from C++ is not its own function, but it is of C program. This will make compiler to search and compile function code in C.

Even though function is in C language, we have to declare the function within C++ program also, to call that function within it. Therefore while declaring the function within C++, we tell the compiler that it is a C function by appending ‘extern “C”’ before the function declaration.
    extern"C"voidCFunctionExample();

Once it is declared as ‘extern C’, function can be called anywhere in the C++ program like any other normal function we call. Below code snippet shows how C function is declared and called within C++ program. The definition of declared function will be there somewhere in C program.

extern"C"voidCFunctionExample (); //declaring C function within C++ program

int main(){
	CFunctionExample (); //calling C function within C++ Program
}

 125. What if we want to declare multiple C functions at once in our C++ code?

Above example shows how to declare single C function within C++ program. Suppose we have more than one C functions to be called from C++ program. Then we need to declare all of them first as ‘extern C’. But we need not add ‘extern C’ before all the function declaration. We can make a block of ‘extern C’ and within it all C functions can be declared. Once functions are declared as ‘extern C’, then it can be called anywhere in C+ function like we call any other C++ functions.

extern"C" {//declaring C function within C++ program
        void CFunctionExample1 ();
        void CFunctionExample2 ();
        void CFunctionExample3 ();
};
int main(){
//calling C function within C++ Program
	CFunctionExample1 (); 
        CFunctionExample2 ();
        CFunctionExample3 ();
}

126. What is a memory leak in C++?

In C++, most of the time we deal with objects. When we say object, it is a place holder in the memory. That means, when we create an object, we/ developers have to allocate enough memory space so that it can hold all its members within it. Similarly, when the use of the object is over or program is complete, it is responsibility of developer to deallocate the memory allocated to the objects.

Suppose developer has not deallocated the memory at the end of the program, then the memory allocated to that object will not be released and show that it is reserved. This piece of memory location will not be available for any other program or object until it is released by the developer. In other words, this memory is waste throughout. Such memory is called memory leak.

127. What problems can be caused by memory leaks?

Like we saw above, memory leak is the one where allocated memory is not deallocated by the programmer. Suppose there are lots of such memory leaks in the program. This will cause the program to run out of memory and its performance will slow down. As the number of memory leak increases, and makes the program to run out of memory, the program will crash. Therefore memory leak is not acceptable in a program.

128. Provide an example of a memory leak in C++?

Below is the simple program to show how a memory leak can happen. We have declared and allocated memory to an integer pointer. Then we have assigned value to it. But at the end of the program, we have not deallocated the memory. The program will compile without any error and execute properly. It will not show any memory leaks. But actually there is memory leak because of the programmer not deallocating the pointer memory. It will still show allocated. Therefore developer has to be extra careful while allocating and deallocating the memory in the program.

void main(){
	int *intVal = newint; // allocated memory to hold integer data

	*intVal = 100; // assigns some value to it
	//ends the program without deallocating the memory
}

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

This has very much importance when we create objects in the program. As the name suggests, the delete function is used to delete the object from the memory. When we say deleting the object, it actually means to release the memory held by that object. The object created can be single object or array of objects. That means when object is created, it will have memory allocated sufficient to hold that object itself. But when array of objects are created then sequence of memory location is allocated to hold each objects in the array.

Therefore when we have to delete the object, if we just say delete, then it will release the memory held by that object alone. If we use delete to release the memory held by array of objects, then it will not be able to release all the memories held by the array. It will release partial memory and hence there will be memory leak. Therefore, if we have to release the memory held by the array of objects, then we have to use delete [], so that all the objects in the array are deleted.

voidtestObject(){
	string *strArr = new string[10];
	string *str = new string;
	deletestr; // deletes the object str
	delete[] strArr; //deletes array of string objects
}

In above code snippet, an object str is deleted by using simple delete function whereas array of string objects strArr is deleted by using delete []. If we use delete to release the memories of strArr, it will not release all 10 object’s memory.

130. What happens if you use delete when you should use delete[ ] instead?

If we have used delete on the array of object where we are supposed to use delete [],it will not release all the memory held by the array. Hence it will show some of the memory as still in use whereas we will think that we have released all the memories. That means, it will create memory leak in the system. Therefore we have to be very careful while using delete and delete [] on the objects.

132. What happens if you use delete when you should use delete[ ] instead?

If we have used delete on the array of object where we are supposed to use delete [],it will not release all the memory held by the array. Hence it will show some of the memory as still in use whereas we will think that we have released all the memories. That means, it will create memory leak in the system. Therefore we have to be very careful while using delete and delete [] on the objects.

133. What’s the difference between a class variable and an instance variable?

Both class variable and instance variables are associated with class and are members of the class. In order to differentiate their functionality or use, different terminology is used. Like we said, both of them are members of the class, i.e.; both instance variable and class variables are declared within the class. When we create an object out of a class, a copy of its class variables are created for each object; which is known as instance variable. But same copy of the class variable is maintained for all the objects of the class. Therefore class variable is also known as static member of the class. Let us try to understand the difference using an example.

classmemberExample{
public:
	intinstVar;    //instance variable
	staticintclassVar; // class variable
};

void main(){
	memberExample me1;
	memberExample me2;

	me1.instVar = 10;  // one copy of instance variable
	me1.classVar = 50; // single copy of class variable

	me2.instVar = 20; // another copy of instance variable

	cout<<"me1.instVar = "<< me1.instVar;
	cout<<"me1.classVar = "<< me1.classVar;
	cout<<"me2.instVar = "<< me2.instVar;
	cout<<"me2.classVar = "<< me2.classVar;
}

In above program, instVar is the instance variable. When we create multiple object of the class, a copy of the variable is created for each object. Hence we can assign different values to instVar of different objects. The variable classVar is the class variable which is static. Hence we cannot have multiple copies of it for different objects. In addition, its value remains constant and we cannot change its value.

134.    Can static function access non-static member variables of class?

In C++, everything is revolving around class and its objects. In other words, all the variables and functions are created inside a class; and are accessed by using objects of that class. But sometimes, it is required to create some variables and functions which are independent of class or objects. Such variables and functions are created by using a keyword ‘static’.

A static function is the one which can be called without referencing to any objects. But any other non-static variables or functions cannot be called without any objects. They need to have class objects to define and reference them. Therefore when we try to access non-static members (either variables or functions) of a class through static function, it is similar to access non-static members without any class objects – which is against the rule. Hence we will not be able to access any non-static members using static functions.

135. Do static functions have a “this” pointer?

“this” pointer is used to reference the instantiated object of the class. That means, ”this” pointer exists only when a class and its objects exists. But static function is the one which is independent of the object- it is called without referencing to any object. Therefore we cannot have any “this” pointer within static function nor pass to the static function.

Constructor and Destructor in inheritance

136. Suppose you are given the C++ code below. What would be printed out – and in what order?

classBase{
public:

	Base()	{
	cout<<"Inside Base constructor"<<endl;
	}

	~Base()	{
		cout<<"Inside Base destructor"<<endl;
	}
};

classDerived : publicBase{
	public:
	Derived()	{
		cout<<"Inside Derived constructor"<<endl;
	}
	~Derived()
	{
		cout<<"Inside Derived destructor"<<endl;
	}
};
void main(){
	Derived x;
}

In the above program, we have two classes – Base and Derived. Base class is the original class and Derived class is derived from Base class. Inside the Base and Derived classes, we have two functions to construct the object and to destruct the object. In the main function Derived class object is created. When Derived class object, x is created in the main function, it will automatically call the constructor of the Derived class. Since Derived class is derived from Base class, before calling the constructor of the Derived class, it will jump to create the constructor of the base class (that means, it will allocate memory to hold the Base class object). Hence the message inside the Base class constructor will be printed first and then message inside the Derived class constructor will be printed.

Once the Derived class object is created, main function is complete. Then it will automatically start releasing the memory held by the objects in the program. Now, releasing memory will happen in reverse order. i.e.; message inside the Derived class destructor will be printed first and then Base class destructor will be printed.
While constructors are called, first all the base class (parent class) constructors are called first and while destructors are called all the derived class (child class) destructors are called first. Hence the output of above program would be :


137. Does C++ support multiple inheritance?

Multiple inheritance is the one where a class is derived from more than one base class. That means, class C is derived from base class A and B.

For example, child class is derived from both Fatherand Motherclass. Therefore child class is depicting multiple inheritance from both Father and Mother.

138. What problems could be caused by multiple inheritance?

Because of multiple inheritance, there is a possibility of diamond problem. Hence we need to be careful while creating multiple inheritance in programs.

Can you change the “this” pointer?

139. Suppose you are given the code below – will it compile?

classX{
public:	voidsomeFunction(X *x){
	this = x;
        }
};

This code will not compile. This is because  ‘this’ is the parameter which refers to the current object. Therefore it cannot be modified. Here we are trying to assign value to current object using ‘this’ parameter. As it cannot be modifiable, this type assignment will throw error. Hence it will show below error when compiled.

Function Templates in C++ example

140. Explain function templates in C++, and provide an example.

We now clearly know that in C/C++, we have all the variables with different data types, and we use functions to deal with different functionalities of the program. But when we write a function, we can pass only particular data types to it as parameter. If we need a same functionality for different data type, then existing function will not work. We have to write totally new function with different data type; but the same logic. For example, consider a function to add two numbers. This number can be integer or float. If we write a function to add two integer numbers, then the same function cannot be used to add two float numbers. We have to write the new function to add two float numbers. But in both the functions, the logic is same except their data types. This will increase the code length as well as complexity in the program.

If we have single function that can handle different data types then our code will become simple and easy to understand. This can be achieved by the use of function template. Like the name says, function template acts like a template which contains the logic to be executed. When function is called, the datatype of the parameters will be decided and accordingly the function will be executed. That means, while adding two numbers, we just perform ‘A+B’ without considering its datatype in the function. But when function is called, function will decide which datatype of numbers are added depending on the variable datatype passed.

The function template is written as shown below:

template// template prefix
int AddNum(T&num1, T&num2){
	T result; // result will take the datatype depending on the datatype is passed to the function

	result = num1 + num2;

	return result;
}

void main(){
	int intNum1=40, intNum2 = 20, intSum;
	float fltNum1 = 3.14, fltNum2 = 5.23, fltSum;

	intSum = AddNum(intNum1, intNum2);  // calls the function with integer parameter
	fltSum= AddNum(fltNum1, fltNum2);// calls the function with float parameter
}

Here AddNum is the function used to add two numbers. We have not defined the datatype for the parameter passed to it. Instead we have added the first line as ‘template , indicating the function below is the template. Here ‘class T’ indicate T is of type ‘class’- that means ‘class’ here denotes the datatype of T. Now T gets the datatype that is being passed while function being called. Same datatype exists till the function execution end. In the code above first function call is to add integer numbers. Hence T gets its datatype as ‘int’. Therefore, num1, num2 and result in the function are considered as integer. In the second call, we have passed float variables. Therefore, num1, num2 and result in the function are considered as float. But we have called the same function to add two integers as well as two float numbers. In this case, calling a function is similar to any other functions.

C++: The compiler and function templates

141. How does the compiler deal with function templates in C++?

When we create a function template and call the function by passing different types of parameter, it is the compiler who actually handles the function to deal with different data types. But how compiler will get function definition for the types of parameter passed? What if does is, in the background it creates function definition for the function calls present in the program. To be clearer, in our first example above, we have function call to add integer and float numbers. Therefore, in the background compiler creates function definition for integer addition and float addition using the template. But these definition will not be visible to the developer. It will not create any other definition for the types that are not being called in the program – for example, addition of double is not called and hence its definition will not be created.

C++: Function template with more than one type parameter

142. How would you create a function template with more than one type parameter?

Consider another example. Say, here we are passing two different types of parameters to the function. Then we have to set the template to have two different parameters like below.

template<classT1, class T2>// template prefix
int AddNum(T1&num1, T2&num2){
	T1 result; // result will take the datatype depending on the datatype is passed to the function
	result = num1 + num2;

	return result;
}

void main(){
	int intNum1=40, intNum2 = 20, intSum;
	float fltNum1 = 3.14, fltNum2 = 5.23, fltSum;

	intSum = AddNum(intNum1, fltNum1);  // calls the function with integer parameter
	fltSum= AddNum(fltNum1, fltNum2);// calls the function with float parameter
}

Here we have set two types of parameters. T1 can be integer or float or double. T2 can also be same as T1 or different type. But the result is set to be of type T1. Now both T1 and T2 take their types depending on the parameters passed to it. This is how using single function template we execute the function for different data types.

C++: #include ” ” vs. #include <>

143. What is the purpose of #include in C++?

When we write programs in C/C++, it will run for pages. This is because we mostly use these types of programming languages for very big applications like video games, financial applications, or similar kinds of requirements. These types of requirements are not small and there will be lots of validations required. In addition, these validations and set of codes will be required to be called or written again and again.
If we write the code in a sequence – writing all validations and function calls one after the other as the requirement goes, the code length will go on increasing. Similarly, we will be wasting time and space over the same thing for multiple times. Also, these sequences of codes will be confusing to the same or different developer when he is reviewing the code, and would be required for different set of programs that are related to the same program/application or different program/application.

Therefore, we can segregate all the validations and repetitive set of codes into respective functions and we can place them in a separate file. When these functions are required in the current executing program, we can just add them in our current program by including those files in the program. When we include those files in the current program, it will just symbolize us that those functions are included in the program. But actually it will be replaced by its actual code lines when the program is being compiled.

That means, program will look smaller and meaningful for the developer and user; at the same time it will have all the required functionalities and code within it. By this way we can make the code more efficient.

144. What’s the difference between using quotes and angled brackets in the include statement?

The main purpose of using “include” statement in the code is to add header files within current program. These header files can be predefined at the time of developing C/C++ or may be defined by the user. At both these cases, these header files will be saved at different locations. When header files are predefined, these header files will be saved in implementations of C++. It will be available in the folders that are created during the installation of C/C++. But the use defined header files will be saved in the same directory as the program is saved. In case it is not saved in the same directory as the program, compiler will search them in other directories. Hence it is very much essential for us/developers to tell the compiler which is predefined file and which is user defined header file. This will save time for searching for the files in the system directories.

Therefore we use angular brackets to indicate the compiler that those header files are predefined and needs to be searched in the folders where C/C++ implementations are placed. For example, in C++, iostream is the header file which is predefined and has all the files required call input/output functions (when we call cin or cout in C++, it actually has set of codes defined within cin and cout function respectively. These functions are defined within iostream).

When quotes are used, compiler will understand that those header files are saved in the user’s program folder and it will search for them in those folders.

145. How do I decide to use angled brackets or quotes in the include statement?

When we need to include predefined files like iostream, string, math, malloc etc. in the current program, we have to use angular bracket. It will indicate the compiler that they are predefined header files and for their source code C/C++ implementation folders needs to be searched- especially the ‘include’ folder as shown in above image snippet.

When we need to include user/developer defined codes within the program which are saved in different files, then we need to include quotes to indicate the compiler that they are user defined files. They need to be searched in the folders where user saves his programs.

146. How do you add predefined header files in the program?

Predefined header files like iostream, string, malloc, time etc. are added into the program by using angular brackets in the “include” statement. It will indicate the compiler that they are predefined files of C/C++. We need not write “.h” after the files names for such header files.

147. How do you add user defined files in theprogram?

User defied files can be included in the program by using quotes in the “include” statement. This will indicate the compiler that they are user defined files. Here we need to mention the extensions of the files too.

C++: Name Hiding

148. What is name hiding in C++?

We know what is function overloading. It is the method where same function is created again for different datatype or number of parameters. Here function name will remain same and the function call will decide which function definition needs to be called depending on the parameters passed to it. Usually function overloading is done within the same class.

Suppose we have a function SwapNum in parent class. What will happen in derived class? A copy of SwapNum is created in the derived class too. Imagine we have overloaded the same function SwapNum in the derived class. That means, say in parent class we had SwapNum for swapping integer numbers and in the derived class we have it for characters. And in the main function we have called integer swap using child class object. What will happen? Will it execute the swap?

classparentClass{
public:
	voidSwapNum(intnum1, intnum2){
		int temp;
		temp = num1;
		num1 = num2;
		num2 = temp;
	}
};

classchildClass :publicparentClass{
public:
	voidSwapNum(charchr1, charchr2){
		char temp;
		temp = chr1;
		chr1 = chr2;
		chr2 = temp;
	}
};

void main(){
	childClassch;
	int intVal1 = 30, intVal2 = 50;

	ch.SwapNum(intVal1, intVal2);
}

It will swap the numbers by considering 30 and 50 as ASCII value. That means it will convert them to characters and use SwapNum function of child class itself. It will not use integer swap in the parent class. Why? This is because when the function is called using child object, the child class hides the function that exists in its parent class. It stops the pointer at child class itself and allows to evaluate it using that function. Parent class function will not be used at all. This is what happens when we overload functions in their derived classes. But actually we are expecting the function call to use parent class function.

In below screenshot, the function call clearly shows which function is being called – the function definition below function call shows its parameter as char, which is of child class.

149. What is the solution to Name Hiding ?

The solution for this type of name hiding is to use ‘using’ keyword in the child class. When we do this, a copy of parent class function is also created in the child class. So when function is called from the main class, it will call parent class function itself.

classparentClass{
public:
	voidSwapNum(intnum1, intnum2){
		int temp;
		temp = num1;
		num1 = num2;
		num2 = temp;
	}
};

classchildClass :publicparentClass{
public:
	voidSwapNum(charchr1, charchr2){
		char temp;
		temp = chr1;
		chr1 = chr2;
		chr2 = temp;
	}
};

void main(){
	childClassch;
	int intVal1 = 30, intVal2 = 50;

	ch.SwapNum(intVal1, intVal2);
}

In below screenshot, the function call clearly shows which function is being called – the function definition below function call shows its parameter as int, which is of parent class.

150. What is C++?

C++ is an object oriented language invented by Bjarne Stroustrup in 1985. It is a powerful, general purpose language. It has almost all features of C language. In addition to that it has some additional features like simplified memory management, class data type etc. The class is the main feature of the C++ language which makes it as object oriented language.

C++ language can be used for any small programs or for any large applications. It can also be used for making CGI scripts or console only DOS programs. It allows the user to programs to perform almost all the requirements. Hence it is a very powerful language to develop any kind of programs.

151. What is the difference between realloc() and free()?

The realloc function is used to reallocate or redefine the memory allocated to the objects. It changes the size of the memory allocated to the object and assigns a new pointer to the memory block in the memory.

The free function is used to release the memory block held by the object. It de-allocates the memory allocated to the object using malloc, realloc or calloc functions.

152. Base class has some virtual method and derived class has a method with the same name. If the base class pointer is initialized with derived object, then which method will be called when virtual method is called?
a.    Base method
b.    Derived method

b) it will invoke derived class method.

153. What is function overloading and operator overloading?

Function Overloading: This is the method where multiple functions are defined with same name but different functionalities. These functions may have different sets of parameters or at least different types of parameters. When the function is called in the program, the compiler checks for the number of parameters passed, their type, order of arguments passed etc. and decides which function to be called. Hence compiler will not fail to call the right function. Below is the function which is overloaded 6 times based on the parameters passed, their type and position of parameters. When function is invoked, respective functions will be called.

Operator overloading: It is the method of overloading the functionality of any operator with new definition. This can be applied on variables or any objects. For example, the addition operator ‘+’ is generally used for adding any two numbers. It can be overloaded to combine any two strings or merge any two numbers.

154. What are the advantages of inheritance ?

It allows code reusability. This saves time in program development and encourages the reuse of proven and debugged high-quality programs, thus reducing issues after a system becomes functional.

155. What is the difference between declaration and definition ?

The declaration gives the type to the variable and structure to the class. The definition gives the value to the variables and values to class members. The declaration of the function gives the skeleton of the function while definition gives the actual implementation of the function.

Eg:-

intNum1;// declaration of a variable
voidsampleFunction ();// declaration of a function

Num1=10// definition of the variable

void sampleFunction (){
        cout <<”This is the definition of a function”;
}

 156. What is inline function?

Inline function is a function where function call in the program will replace the function definition. In general, when a normal function is being called, the program execution control will be stopped at function call and jumps to execute function definition, and then returns back to calling program. In the inline functions, the program control will not jump, but it replaces the function call by its definition. Hence the program will be executed as if it is a continuous program. It increases the performance of the program.

157. Write a program that ask for user input from 5 to 9 and calculate average of them?

#include
usingnamespacestd;

voidmain(){
    intMAX=4, Total=0, average, num;
    for(inti=0;i<MAX;i++){
        cout<<"Please input the numbers between 5 and 9: ";
        cin>>num;
        while(numb<5||num>9){
            cout<<"Invalid Entry!! Please re-enter the number: ";
            cin>>num;
        }
        Total=Total+num;
    }
    average=Total/MAX;
    cout<<"The average number is: "<<average<<"\n";

 158. Write a short code using C++ to print out all odd number from 1 to 100 using a for loop?

#include
usingnamespacestd;

voidmain(){
    for(unsignedinti=1;i<=100;i++)
    if(i&0x00000001)
        cout<<i<<",\"";
}

 159. What is public, protected, and private?

These are the access specifiers in C++.

  • Private: This type of data and functions are accessible only for the class objects in which they are declared. It cannot be accessed outside the class.
  • Public: These type of data and functions are accessible outside the class also.
  • Protected: These data members and functions are accessible by the class in which it is defined as well as in the derived class.

160. What is virtual constructors/destructors?

Virtual constructor: We cannot have virtual constructor, it will be a syntax error. Constructors are meant for allocating space for the objects created. Hence if we make constructor virtual, it will not allocate any memory space but object will be created which is not correct.

Virtual destructors: In most of the cases, C++ programs are with inheritances. That means it has base class and subsequent derived classes. Therefore when we create an object using derived class, its base class properties are also inherited to the object. Similarly when we delete the object, its properties should be deleted till the base class. This will not happen, if we simply delete the object using delete operator. This will also not happen if we have destructor only in the derived class. We need to have them in base class also. Simple destructor in base class will not automatically delete the derived class object properties. Base class destructor should be virtual for this. That means any virtual function will be implemented in its derived classes and calling this function makes sure, it executes the code on behalf of base class too ( virtual destructor in base class will not have any body, but it will be implemented in derived class).

161. Is multilevel and multiple inheritance supported in C++?

C++ supports multi-level inheritance.

162. What are the advantages of inheritance?

  •    It allows code reusability.
  •     Reusability saves time in program development.
  •     It helps to reuse verified and debugged software, thus reducing problem after a system becomes live.

163. What is the difference between an array and a list?



164. What is a template?

Template is used to create a generic function that takes parameters of any data type and its return value with any data type. This gives the flexibility to pass any type of parameters to the function and get any type of result. The user need not know about the function in this case.
165. Define a constructor  and howis it called (2 methods)?

Constructor is a function in the class with the same name as class. It will be called automatically when the object of that class is created. It is used to specify how to initialize the object of the class.
It can be called implicitly when the object is created or by explicitly calling the constructor like we call any other function.

166. Explain differences between eg. new() and malloc()?

167. What is the difference between class and structure?

167. What is RTTI?

Runtime type identification (RTTI) allows us to find the dynamic type of an object when there is only a pointer or a reference to the base type. RTTI is the general way in standard C++ to discover the type of an object and to convert the type of a pointer or reference or address (that is, dynamic typing).

168. What is encapsulation?

It is the method of packaging an object’s variables within its functions or methods.

169. What is an object?

Object is an instance of a class. It has both state and behavior.

170. What is namespace?

Namespaces allow us to group a set of global classes, objects and functions under one unique name. In other words, they help to divide the global scope in sub-scope.The general form of namespaces is:

namespace identifier{namespace-body }

Where identifier is any valid identifier and namespace-body is group of classes, objects and functions that are included within the namespace.
For example:

namespace name_space { int a, b; }

Here, a and b are normal variables associated within the name_space namespace. These variables are accessed from outside the namespace using scope resolution operator ‘::’.

For example, to access the above variables we will write like below:

name_space::a
name_space::b

The functionality of namespaces is especially useful if there is a global object or methods can have the same name than another one, which will create redefinition error.

171. What is a copy constructor and when is it called?

Copy constructor is the one which copies the data members of one object into another object of same class. In simple words, a copy constructor copies objects of the same class.

172. What is a virtual class and friend class?

In a class, data members (variables and functions) can be private, public or protected. When a data member is private, it cannot be accessed by any other class or derived class. Such data members are accesses only by those class objects in which it is being declared. If we declare class as ‘friend’ then, we can access the private data members of that class from other classes too. Such class is known as friend class. This friend class also allows ‘protected’ members to be accessed from other class.

173. What is known as when defining a function in base class to allow this function to be a polymorphic function?

Virtual

174. What do you mean by binding of data and functions?

Encapsulation is the method to bind data and function.

175. What is the difference between an object and a class?


176. What is a class?

A user-defined data type in C++ is known as class. It can be created to address particular problem in the program. Once the class is created, its purpose is served to the user. When a class is created, it is created in such a way that it addresses the real world entities.

E.g: - Person, Student, Shape etc. can  be class with their attributes like name, type, sex, length, breadth etc.

177. What is friend function?

As the name suggests, the function behaves as a friend to a class. Since it is a friend of a class, it can access private and protected members of that class. A friend function is not a member of any class. But it must be programmed in the class definition.

178. What is abstraction?

Abstraction is the method of hiding unwanted details from the user and wrapping it inside the class.

179. What are virtual functions?

A virtual function permits derived classes to replace the execution provided by the base class. It is responsibility of the compiler to call the right function, even if the object pointer is pointing to derived class or base class. This lets algorithms in the base class to be replaced in the derived class, even if end user don't know about the derived class.

180.    What is a scope resolution operator?

A scope resolution operator (::), is used todescribe the member functions of a class outside the class.

181. What do you mean by pure virtual functions?

A pure virtual member function is also a member function that has to be redefined in the derived class, even though it is present in the base class. Normally these member functions will not have any definition in the base class. Pure virtual functions are equated to zero while declaring itself.

class Shape { public: virtual void draw() = 0; };

182. Why arrays are usually processed with for loop?

The real uses of arrays are because of their ability of using an index variable to traverse the array, accessing each element with the expression a[i]. Here I acts as a counter, incrementing from 0 to a.length -1. That is what a loop does.

183. What problems might the following macro bring to the application?

#define sq(x) x*x, here if ‘++a’ is passed to the macro, it will calculate ‘++a * ++ (++a)’, which is not actually required. For example, say we have assigned 4 to a, then our expected result is 16. But the macro will evaluate 4 to 5 and then 5 to 6 and give us 30 as answer.

int a = 4;
sq(++a); // (++4 )* (++ 5) = 30

184. What is wrong with this code?

T *p = new T[10];
delete p;

When we have created an array of objects, it has to be deleted using delete [] operator, not simply delete.

185. What is wrong with this code ?

T *p = 0;
delete p;

Answer: Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either. If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete at all.

186. How do you decide which integer type to use?

It depends on our requirement. When we need to store an integer with 1 byte (means less than or equal to 255) we need to use short int, for 2 bytes we need to use int, for 8 bytes we need to use long int.
A char is used for 1-byte integers, a short is used for 2-byte integers, an int is generally used for a 2-byte or 4-byte integer (though not necessarily), a long is used for a 4-byte integer, and a long is used for a 8-byte integer.

187. What does extern mean in a function declaration?

If we need to use a function outside the file in which it is defined, we can declare it using the keyword extern. This makes a variable, function definition, makes it to be used within the source file as well as in other files too. It does not alter the definition of the variable or function. If there is any variable or function declared as extern already exists in the file scope without extern, and its reference is for such variable or function within the file itself. If it does not exists, then it searches for any extern variable or function in other files.

188. What can I safely assume about the initial values of variables which are not explicitly initialized?

It depends on complier that we use for the program. It might assign some garbage value to a variable if it is not initialized.

189. What is the difference between char a[] = “string”; and char *p = “string”;?

In the first initialization, 6 bytes are allocated to the variable and is fixed, where as in the second case if *p is assigned to some other value then its  allocate memory will also change.

190. What’s the auto keyword good for?

An auto keyword declares an object with automatic storage duration. That means the object will be destroyed at the end of the objects scope which can be block, function or a program itself. All variables in functions that are not static variables and which are not dynamically allocated have automatic storage duration by default.

191. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?

typedef char* (*functiontype1)(void);

typedef functiontype1 (*functiontype2)(void);
functiontype2 myarray[N]; //assuming N is a const integral

192. How do we initialize a pointer to a function?

Pointer to a function can be initialized in following way:

#include
usingnamespacestd;

voidfunc(intx)
{
}
voidmain()
{
    void(*fp)(int);
    fp=func;
    fp(1);
}

193. How do you link a C++ program to C functions?

It can be achieved by using extern "C" linkage specification before the C function declarations.

194. What are the ways are there to initialize an int with a constant?

There are two types of initialization methods in C++ .
The first format is the traditional C notation.
The second format is the constructor notation.
int obj = 123;
int obj (123);

195. What is a conversion constructor?

Conversion constructor is the one where constructor accepts one argument of a different types.

196. What is the difference between a copy constructor and an overloaded assignment operator?

A copy constructor create a new object by using member variables of argument object. An overloaded assignment operator assigns the member variables of an existing object to another existing object of the same class.

197. Explain the ISA and HASA class relationships. How would you implement each in a class design?

A special class is called as ‘IS A’ class if it has a new or special features than another class. Forexample, an StudentISA Person. This relationship can be best implemented with inheritance. The Studentclass is derived from the Person class.

A class may have an instance or object of another class. For example, an Student "has" a Teacher; therefore the relationship of STUDENT class with TEACHER is a ‘HAS A’ relationship. This relationship is best implemented by having an object of the TEACHER class inside the STUDENT class.

198. What is a mutable member?

A member variable is said to be mutable, if it can be modified by the class even when the object of that class or its member function performing the modification is a const.

199. What is an explicit constructor?

It is a constructor declared with the explicit keyword. The compiler does not call the explicit constructor to implement an implied conversion of types. It is mainly reserved explicitly for construction.

200. Describe run-time type identification.

At run time, using typeid or dynamic cast operator, if program determines the type of an object, then it is known as run time type identification.

201. Will the following program execute?

#include
usingnamespacestd;

voidmain()
{
    void*vptr=(void*)malloc(sizeof(void));
    vptr++;
}

It will throw an error, as arithmetic operation is performed on void pointers.

202. What is a modifier?

It is also known as‘mutators’ or modifying function. It is a member function that modifies the value of at least one data member of the same class. In other words, it is an operation that modifies the state of an object.

203. What is an accessor?

An accessor is a class operation where state of an object cannot be modified. In general, accessor functions has to be declared as const operations .

204. Differentiate between a template class and class template.

205. What is a dangling pointer?

It a pointer which is accessed after it is deleted. In other words, the object’s pointer might have served its purpose and programmer would have released his memory or a function may be returning the address of automatic variable (which is specific for function alone). In these cases, the pointer is called as dangling pointer – a pointer with no address.

206. Differentiate between the message and method.



207. What is an adaptor class or Wrapper class?

A wrapper class or adaptor class is a class with no functionality of its own. Here its member function is used to hide all the details like its components, third party software details or an object that is non-compatible interface or non-object oriented implementation.

208. What is a Null object?

Null object isalso an object of a class and indicates that such object of the class does not exist. One can find its use while returning the object value from a function where function could not find such value and will return null object.

209. What is class invariant?

Class invariant is the state that defines all the valid states of an object. It is helpful in determining the correct working of a class. Class invariants should have object’s state when an object is created, and those states must be retained under all operations of the class. In particular,classinvariants contain both preconditions and post-conditions for all actions or member functions of the class.

210. What do you mean by Stack unwinding?

It is a process seen during exception handling. When an exception is raised, the destructorsare called for all local objects within the exception where exception was thrown and where it is caught.

211. What are proxy objects?

An Object that is used for other object is known proxy object or surrogate object.

212. Name some pure object oriented languages.

Some of them are : Java, Smalltalk, Sather, Eiffel.

213. What are C++ storage classes?

The storage classes are:

  •     Auto
  •     Register
  •     Static
  •     Extern

214. What is virtual inheritance?

When an inheritance is virtual, only one copy of eachobjectsis created.

215. What is the use of exception handling?

It is the method of capturing the errors in the program, which can be captured and handle in the program for its smooth execution.

216. What is EOF?

EOF stands for End of File; It is used to verify for the end of file when a file is being read.

217. Define the parameterized macros?

Macros with parameters are known as parameterized macro. It is the macro that consists of template with insertion points for the addition of parameters to it.

218. What is overflow error?

Overflow error is one of thearithmetic errors. It occurs when the actual space provided by the system is lesser and the result is having greater size.

219. What is a nested class? Why can it be useful?

Nested classes are used to organize code and to control the access and dependencies. Nested classes also have access rules just like other parts of a class and that class is a class bounded within the scope of another class.

220. What are the disadvantages of C++?

  • It's not pure object oriented programming language.
  •     It’s a Platform dependent.
  •     C++ does not give excellent graphics when compared with java.
  •     It’s case insensitive.
  •     C++ hasfewer features as compared to Java& C#.
  •     It’snot applicable in web environment.
  •     It does not offer very strong type-checking.
  •     C++ code is easily liable tohave errors related to data types, and datatype conversions.
  •     It does not give efficient methods for garbage collection.
  •     No support for threads like in Java

221. What is callback function?

Callback function is the type of pointer for a function.

222. What is the use of tellg ()?

tellg () provides details about the current position of input/get pointer.

223. What is the use of tellp ()?

It is used for the pointerposition i.e.; it provides the current position of output/put pointer.

C++ Access Control

224. Explain the difference between struct and class in terms of Access Modifier.

All the data members of struct are public by default whereas data members of class are private by default.

struct Student
{
	int rollno; //Public members
	int marks1, marks2;
};
class Student
{
	int rollno; //private members
	int marks1, marks2;
public:
	void show(int r); // to print marks
	void sum(int r); // to add the marks
};

225. Explain private, public and protected Inheritance?

  • Private Inheritance : In this type of inheritance, all the public and protected data members of a class become private in the derived class. Below is the example of private inheritance of the derived class (we need not mention private while deriving from base class. By default it is considered as private)

  • Public Inheritance : In this type of inheritance, all the public and protected data members of a class remain same and they do not change.

  • Protected Inheritance : In this type of inheritance, all the public and protected data members of a class become protected in the derived class. Below is the example program for protected inheritance. Since all the data members become protected, we cannot access them in the main function. But they are accessible in the derived class.
#include"stdafx.h"
#include
usingnamespace std;

classTest {//base class
public:int x;
protected: int y;
public:	Test() { //constructor of base class
			x = 0;
			y = 0;
}
};

classderivedTest : protectedTest{ //derived class
public:
	derivedTest(){ //constructor of derived class
		x = 5;
		y = 10;
	}
};

int main()
{
	Test t1;//base class object
	derivedTest dt1; //derived class object

	cout <<"Values of x and Y using respective object is...."<< endl;
	t1.x = 100;
	//t1.y = 200;//since it is a protected member, main function cannot modify its value
	cout <<"values of x and y in Test class....."<< endl;
	cout <<"x value is "<< t1.x << endl;
	//cout << "value of y is" << t1.y<< endl; //since it is a protected member, main function cannot modify its value

	dt1.x = 500;
	//dt1.y = 1000;//since it is a protected member, main function cannot modify its value
	cout <<"values of x and y are in derivedTest class....."<< endl;
	cout <<"value of x is"<< dt1.x << endl;
	//cout << "value of y is" << dt1.y << endl;//since it is a protected member, main function cannot modify its value

	return 0;
}

 

226. What is the default access level?

The default access level in a class is private.

227. Explain private, protected and public access control in C++?

  • Private: It is the default access control in the class and these members are accessible by the same class objects alone. These data members are not accessible by any other class or derived class. In below example, the class has all private members (default access control).  Hence the constructor is also private member of the class. Therefore it does not allow creating object of it, saying cannot access private member of the class.

After making constructor as public, it shows error while accessing member variable ‘x’ as it is private. That means private members are not accessible to any of the derived class or outside the class.