C++ Interview Questions and Answers
1)What is a memory leak? How can we avoid it?
Ans: A memory leak can be avoided by making sure that whatever memory has been dynamically allocated will be cleared after the use of the same. for example
int main()
{ char *myCharData[20];
for (int nLoop =0;nLoop < 20; ++nLoop) { myCharData[nLoop ] = new char[256];
strcpy(myCharData[nLoop],”SABITH”);
……
}
……………………
/*Some manipulations here using myCharData*/
/*Now here we have to clear the data. The place can vary according to ur program. This being a simple program,u can clear at the end*/
for(int nLoop =0;nLoop < 20; ++nLoop)
{
delete[] myCharData[nLoop ];
}
return 0;
2) How do you write a program which produces its own source code as its output? Ans: Write this program and save it as pro.c….run….it will show the program to the consol and write the source code into data.txt file……… #include void main() { FILE *fp,*ft; char buff[100]; fp=fopen(“pro.c”,”r”); if(fp==NULL) { printf(“ERROR”); } ft=fopen(“data.txt”,”w+”); if(ft==NULL) { printf(“ERROR”); } while(getc(fp)!=EOF) { fscanf(fp,”%s”,buff); printf(“%s\n”,buff); fprintf(ft,”%s\n”,buff); } }
3) What are the things contains in .obj file? ( compiled result of .cpp file ) Ans: C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.
4) What is the difference between following initialization. int iVar1; int iVar2 = int(); and which one of two should we prefer always and why? Ans: In the first case a variable will be created in memory with the default base type value (depending upon compiler 2 compiler) bcoz it is not initialized. in the second case the variable will be created in the memory with the value returned by the function int() (if it is a user define function) the second statement should have been int *i = new int();
5) What is the difference between Object and Instance? Ans: An instance of a user-defined type (i.e., a class) is called an object. We can instantiate many objects from one class. An object is an instance or occurrence of a class.
6) How is static variable stored in the memory? (if there are 2 functions in a file, and the static variable name is same (ex var) in both the function. how is it keep separately in the memory). Ans: C++ uses name mangling when storing both local and global static variables at the same place. The local static variables have function name and the global variables will have the file name. Essentially the compiler uses the namespace to distinguish between local and global static variables.
7) what is the difference between wait() and delay()? Ans: Wait() and delay() works same but works on different platforms. Wait(2) will wait for processing for 2 seconds on Linux/Unix while delaying (2000) with a wait for 2 seconds but on DOS or Windows. so wait(2) on Linux == delay(2000) on DOS Delay() is under while one can directly use wait in his/her program.
8) Why always array starts with index 0 Ans: Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.
9) Can main() be overridden Ans: In any application, there can be only one main function. In c++, main is not a member of any class. There is no chance of overriding
10) What is the difference between macro and inline()? Ans: 1. Inline follows strict parameter type checking, macros do not. 2. Macros are always expanded by a preprocessor, whereas compiler may or may not replace the inline definitions.
11) How can double dimensional arrays be dynamically initialized in C++? Ans: Example of how to dynamically initialize double dimensional arrays: int num[2][3] = {34,32,30,24,22,20}; num[1][1] = 34 num[1][2] = 32 num[1][3] = 30 num[2][1] = 24 num[2][2] = 22 num[2][3] = 20
12) Can destructor be private? Ans: Yes destructors can be private. But according to Standard Programming practice, it is not advisable to have destructors to be private.
13) what is memory leaking in c++? Ans: When a class uses dynamically allocated memory internally, all sorts of problems arise. If not properly used or handled, they can lead to memory leaks & corrupts Data Structures. A memory leak is a situation that occurs when dynamically allocated memory is lost to the program. Char * p; p= new char[10000]; ….. p= new char[5000]; Initially, 10000 bytes are dynamically allocated & the address of those bytes is stored in p. later 5000 bytes are dynamically allocated & the address is stored in p. However, the original 10000 bytes have not been returned to the system using delete [] operator. Memory leak actually depends on the nature of the program.
14) class A() { }; int main() { A a; } Whether there will be a default constructor provided by the compiler in above case? Ans: Yes, if the designer of the class does not define any constructor in the class. then the compiler provides the default constructor for the class.
15) What is the use of virtual destructor? Ans: Virtual destructor is very useful….everyone should use that……if there is no any strong reason for not using virtual destructor….like…One class having two char variable………..so it’s size is two byte……..if u use virtual destructor it’s size will be 6 bytes….4 bytes for virtual ptr… Now if this class have 1 million objects…so 4-megabyte memory will be lost…where all ptr do the same thing…..
16) Why can’t one make an object of the abstract class?Give compiler view of statement Ans: We cant make an object of abstract class because, in the vtable, the vtable entry for the abstract class functions will be NULL, whichever is defined as pure virtual functions… even if there is a single pure virtual function in the class the class becomes an abstract class… if there is a virtual function in your class the compiler automatically creates a table called virtual function table .. to store the virtual function addresses…. if the function is a pure virtual function the vtable entry for that function will be NULL. even if there is a single NULL entry in the function table the compiler does not allow to create the object.
17) In c++ have a default constructor? Ans: Yes C++ does have a default constructor provided by the compiler. In this case, all the members of the class are initialized to null values. These values act as the default values. For eg: My Class me; In the above case since the object is not initialized to any value so the default constructor will be called which will initialize the class with the default values.
18) Have you heard of “mutable” keyword? Ans: The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. SEE FOLLOWING CODE :- ******************************************** class Mutable { private : int m_iNonMutVar; mutable int m_iMutVar; public: Mutable(); void TryChange() const; }; Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {}; void Mutable::TryChange() const { m_iNonMutVar = 100; // THis will give ERROR m_iMutVar = 200; // This will WORK coz it is mutable }
19) What is “strstream”? Ans: Class that reads and writes to an array in memory
20) Can we generate a C++ source code from the binary file? Ans: Technically this is possible, but to my knowledge their no such software available yet. Why is this possible? In program flow, we do like this to generate a binary file. High-level language programming code – low-level programming code- hex code- binary code. How we can do reverse can be illustrated with this example. When I type 0 on screen the ASCII equivalent is 65 and so the binary code will be by converting 65 (01010 0101) so I can recognize this and decode this. The same technique can be used. Some secret mission defense org. I heard have this code splitter from binary to assembly language (low-level language)/ Converter type devices available, they use them for the secret national purpose.
21) Explain “passing by value”, “passing by pointer” and “passing by reference” Ans: There is a major difference between these three are when we want to avoid making the copy of variable and we want to change the value of the actual argument by calling a function. There are we use passing by pointer, passing the reference. We can not perform an arithmetic operation on a reference.
22) Difference between “vector” and “array”? Ans: Vector and Array List are very similar. Both of them represent a ‘growable array’, where you access to the elements in it through an index. Array List, it’s part of the Java Collection Framework and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface. The main difference is that Vector it’s a synchronized object, while Array List it’s not. While the iterator that is returned by both classes are fail-fast (they cleanly throw a ConcurrentModificationException when the original object has been modified), the Enumeration returned by Vector is not. Unless you have strong reason to use a Vector, the suggestion is to use the Array List
23) What are the types of STL containers? Ans: deque hash_map hash_multimap hash_multiset hash_set list map multimap multiset set vector
24) Difference between an “assignment operator” and a “copy constructor” Ans: Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function’s return value, a temporary copy of that object is made. The assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal
25) Can we have “Virtual Constructors”? Ans: No, we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtual constructor by calling an Init method from the constructor which, should be a virtual function.
26) Explain the need for “Virtual Destructor”. Ans: In case of inheritance, objects should be destructed exactly the opposite way of their construction. If the virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.
27) What will happen if I say delete this Ans: If you say “delete this”, you are effectively calling the destructor twice, which could well be a disaster if your class uses the heap. The destructor will be called when you say “delete this” and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibly calling a destructor or using a clause like this.
28) What is the output of printf (“%d”) Ans: Usually the output value cannot be predicted. It will not give any error. It will print a garbage value. But if the situation is main() { int a=1,b=2,c=3; printf(“%d”); } The output will be the value of the last variable, ie. 3
29) What is an algorithm (in terms of the STL/C++ standard library)? Ans: Algorithm in STL consist different searching and sorting algos implementation, which takes start and end iterators of STL container on which algo is going to work.
30) How can you force instantiation of a template? Ans: You can instantiate a template in two ways. 1. Implicit instantiation and 2. Explicit Instantion. implicit instatanitioan can be done by the following ways: template class A { public: A(){} ~A(){} void x(); void z(); }; void main() { A ai; A af; } External Instantion can be done the following way: int main() { template class A; template class A; }
31) What is the difference between operator new and the new operator? Ans: This is what happens when you create a new object: 1. the memory for the object is allocated using “operator new”. 2. the constructor of the class is invoked to properly initialize this memory. As you can see, the new operator does both 1 and 2. The operator new merely allocates memory, it does not initialize it. Whereas the new operator also initializes it properly by calling the constructor.
32) What is the Basic nature of “cin” and “cout” and what concept or principle we are using on those two? Ans: Basically “cin and cout” are INSTANCES of istream and ostream classes respectively. And the concept which is used on cin and cout is operator overloading. Extraction and Insertion operators are overloaded for input and output operations.
33) What are virtual functions? Ans: C++ virtual function is a member function of a class, whose functionality can be overridden in its derived classes. C++ virtual function is, * A member function of a class * Declared with virtual keyword * usually has a different functionality in the derived class * A function call is resolved at run-time
34) We can overload assignment operator as a normal function.But we can not overload assignment operator as friend function why? Ans: If the operation modifies the state of the class object, it operates on, it must be a member function, not a friend function thus all operator such as =, *=, +=, etc are naturally defined as member functions not friend functions Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, it does not have to be a member function and often less confusing. This is the reason why binary operators are often implemented as friend functions such as + , *, -, etc..
35) What is the difference between class and structure? Ans: 1: By default, the members of structures are public while that for class is private 2: structures doesn’t provide something like data hiding which is provided by the classes 3: structures contains only data while class bind both data and member functions
36) What is virtual class and friend class? Ans: Friend classes are used when two or more classes are designed to work together and virtual base class aids in multiple inheritances.
37) Is there any way to write a class such that no class can be inherited from it. Please include code Ans: Simple, make all constructors of the class private.
38) Why can’t we overload the size of, :?, :: ., .* operators in c++ Ans: The restriction is for safety. For example, if we overload. An operator, then we can’t access member in the normal way for that we have to use ->.
39) What is the importance of const. pointer in the copy constructor? Ans: Because otherwise, you will pass the object to copy as an argument of copy constructor as pass by value which by definition creates a copy and so on… an infinite call chain.
2) How do you write a program which produces its own source code as its output? Ans: Write this program and save it as pro.c….run….it will show the program to the consol and write the source code into data.txt file……… #include void main() { FILE *fp,*ft; char buff[100]; fp=fopen(“pro.c”,”r”); if(fp==NULL) { printf(“ERROR”); } ft=fopen(“data.txt”,”w+”); if(ft==NULL) { printf(“ERROR”); } while(getc(fp)!=EOF) { fscanf(fp,”%s”,buff); printf(“%s\n”,buff); fprintf(ft,”%s\n”,buff); } }
3) What are the things contains in .obj file? ( compiled result of .cpp file ) Ans: C++ .obj file holds code and data suitable for linking with other object files to create an executable or a shared object file.
4) What is the difference between following initialization. int iVar1; int iVar2 = int(); and which one of two should we prefer always and why? Ans: In the first case a variable will be created in memory with the default base type value (depending upon compiler 2 compiler) bcoz it is not initialized. in the second case the variable will be created in the memory with the value returned by the function int() (if it is a user define function) the second statement should have been int *i = new int();
5) What is the difference between Object and Instance? Ans: An instance of a user-defined type (i.e., a class) is called an object. We can instantiate many objects from one class. An object is an instance or occurrence of a class.
6) How is static variable stored in the memory? (if there are 2 functions in a file, and the static variable name is same (ex var) in both the function. how is it keep separately in the memory). Ans: C++ uses name mangling when storing both local and global static variables at the same place. The local static variables have function name and the global variables will have the file name. Essentially the compiler uses the namespace to distinguish between local and global static variables.
7) what is the difference between wait() and delay()? Ans: Wait() and delay() works same but works on different platforms. Wait(2) will wait for processing for 2 seconds on Linux/Unix while delaying (2000) with a wait for 2 seconds but on DOS or Windows. so wait(2) on Linux == delay(2000) on DOS Delay() is under while one can directly use wait in his/her program.
8) Why always array starts with index 0 Ans: Array name is a constant pointer pointing to the base address(address of the first byte where the array begin) of the memory allocated. When you use arr[i], the compiler manipulates it as *(arr + i). Since arr is the address of the first element, the value of i must be 0 for accessing it. Hence all arrays begin with an index of 0.
9) Can main() be overridden Ans: In any application, there can be only one main function. In c++, main is not a member of any class. There is no chance of overriding
10) What is the difference between macro and inline()? Ans: 1. Inline follows strict parameter type checking, macros do not. 2. Macros are always expanded by a preprocessor, whereas compiler may or may not replace the inline definitions.
11) How can double dimensional arrays be dynamically initialized in C++? Ans: Example of how to dynamically initialize double dimensional arrays: int num[2][3] = {34,32,30,24,22,20}; num[1][1] = 34 num[1][2] = 32 num[1][3] = 30 num[2][1] = 24 num[2][2] = 22 num[2][3] = 20
12) Can destructor be private? Ans: Yes destructors can be private. But according to Standard Programming practice, it is not advisable to have destructors to be private.
13) what is memory leaking in c++? Ans: When a class uses dynamically allocated memory internally, all sorts of problems arise. If not properly used or handled, they can lead to memory leaks & corrupts Data Structures. A memory leak is a situation that occurs when dynamically allocated memory is lost to the program. Char * p; p= new char[10000]; ….. p= new char[5000]; Initially, 10000 bytes are dynamically allocated & the address of those bytes is stored in p. later 5000 bytes are dynamically allocated & the address is stored in p. However, the original 10000 bytes have not been returned to the system using delete [] operator. Memory leak actually depends on the nature of the program.
14) class A() { }; int main() { A a; } Whether there will be a default constructor provided by the compiler in above case? Ans: Yes, if the designer of the class does not define any constructor in the class. then the compiler provides the default constructor for the class.
15) What is the use of virtual destructor? Ans: Virtual destructor is very useful….everyone should use that……if there is no any strong reason for not using virtual destructor….like…One class having two char variable………..so it’s size is two byte……..if u use virtual destructor it’s size will be 6 bytes….4 bytes for virtual ptr… Now if this class have 1 million objects…so 4-megabyte memory will be lost…where all ptr do the same thing…..
16) Why can’t one make an object of the abstract class?Give compiler view of statement Ans: We cant make an object of abstract class because, in the vtable, the vtable entry for the abstract class functions will be NULL, whichever is defined as pure virtual functions… even if there is a single pure virtual function in the class the class becomes an abstract class… if there is a virtual function in your class the compiler automatically creates a table called virtual function table .. to store the virtual function addresses…. if the function is a pure virtual function the vtable entry for that function will be NULL. even if there is a single NULL entry in the function table the compiler does not allow to create the object.
17) In c++ have a default constructor? Ans: Yes C++ does have a default constructor provided by the compiler. In this case, all the members of the class are initialized to null values. These values act as the default values. For eg: My Class me; In the above case since the object is not initialized to any value so the default constructor will be called which will initialize the class with the default values.
18) Have you heard of “mutable” keyword? Ans: The mutable keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. SEE FOLLOWING CODE :- ******************************************** class Mutable { private : int m_iNonMutVar; mutable int m_iMutVar; public: Mutable(); void TryChange() const; }; Mutable::Mutable():m_iNonMutVar(10),m_iMutVar(20) {}; void Mutable::TryChange() const { m_iNonMutVar = 100; // THis will give ERROR m_iMutVar = 200; // This will WORK coz it is mutable }
19) What is “strstream”? Ans: Class that reads and writes to an array in memory
20) Can we generate a C++ source code from the binary file? Ans: Technically this is possible, but to my knowledge their no such software available yet. Why is this possible? In program flow, we do like this to generate a binary file. High-level language programming code – low-level programming code- hex code- binary code. How we can do reverse can be illustrated with this example. When I type 0 on screen the ASCII equivalent is 65 and so the binary code will be by converting 65 (01010 0101) so I can recognize this and decode this. The same technique can be used. Some secret mission defense org. I heard have this code splitter from binary to assembly language (low-level language)/ Converter type devices available, they use them for the secret national purpose.
21) Explain “passing by value”, “passing by pointer” and “passing by reference” Ans: There is a major difference between these three are when we want to avoid making the copy of variable and we want to change the value of the actual argument by calling a function. There are we use passing by pointer, passing the reference. We can not perform an arithmetic operation on a reference.
22) Difference between “vector” and “array”? Ans: Vector and Array List are very similar. Both of them represent a ‘growable array’, where you access to the elements in it through an index. Array List, it’s part of the Java Collection Framework and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface. The main difference is that Vector it’s a synchronized object, while Array List it’s not. While the iterator that is returned by both classes are fail-fast (they cleanly throw a ConcurrentModificationException when the original object has been modified), the Enumeration returned by Vector is not. Unless you have strong reason to use a Vector, the suggestion is to use the Array List
23) What are the types of STL containers? Ans: deque hash_map hash_multimap hash_multiset hash_set list map multimap multiset set vector
24) Difference between an “assignment operator” and a “copy constructor” Ans: Copy constructor is called every time a copy of an object is made. When you pass an object by value, either into a function or as a function’s return value, a temporary copy of that object is made. The assignment operator is called whenever you assign to an object. Assignment operator must check to see if the right-hand side of the assignment operator is the object itself. It executes only the two sides are not equal
25) Can we have “Virtual Constructors”? Ans: No, we cannot have virtual constructors. But if the need arises, we can simulate the implementation of virtual constructor by calling an Init method from the constructor which, should be a virtual function.
26) Explain the need for “Virtual Destructor”. Ans: In case of inheritance, objects should be destructed exactly the opposite way of their construction. If the virtual keyword is not added before base class destructor declaration, then derived class destructor will not at all be called. Hence there will be memory leakage if allocated for derived class members while constructing the object.
27) What will happen if I say delete this Ans: If you say “delete this”, you are effectively calling the destructor twice, which could well be a disaster if your class uses the heap. The destructor will be called when you say “delete this” and again when that object goes out of scope. Since this is the language behavior, there is no way to prevent the destructor from being called twice. Please refrain from forcibly calling a destructor or using a clause like this.
28) What is the output of printf (“%d”) Ans: Usually the output value cannot be predicted. It will not give any error. It will print a garbage value. But if the situation is main() { int a=1,b=2,c=3; printf(“%d”); } The output will be the value of the last variable, ie. 3
29) What is an algorithm (in terms of the STL/C++ standard library)? Ans: Algorithm in STL consist different searching and sorting algos implementation, which takes start and end iterators of STL container on which algo is going to work.
30) How can you force instantiation of a template? Ans: You can instantiate a template in two ways. 1. Implicit instantiation and 2. Explicit Instantion. implicit instatanitioan can be done by the following ways: template class A { public: A(){} ~A(){} void x(); void z(); }; void main() { A ai; A af; } External Instantion can be done the following way: int main() { template class A; template class A; }
31) What is the difference between operator new and the new operator? Ans: This is what happens when you create a new object: 1. the memory for the object is allocated using “operator new”. 2. the constructor of the class is invoked to properly initialize this memory. As you can see, the new operator does both 1 and 2. The operator new merely allocates memory, it does not initialize it. Whereas the new operator also initializes it properly by calling the constructor.
32) What is the Basic nature of “cin” and “cout” and what concept or principle we are using on those two? Ans: Basically “cin and cout” are INSTANCES of istream and ostream classes respectively. And the concept which is used on cin and cout is operator overloading. Extraction and Insertion operators are overloaded for input and output operations.
33) What are virtual functions? Ans: C++ virtual function is a member function of a class, whose functionality can be overridden in its derived classes. C++ virtual function is, * A member function of a class * Declared with virtual keyword * usually has a different functionality in the derived class * A function call is resolved at run-time
34) We can overload assignment operator as a normal function.But we can not overload assignment operator as friend function why? Ans: If the operation modifies the state of the class object, it operates on, it must be a member function, not a friend function thus all operator such as =, *=, +=, etc are naturally defined as member functions not friend functions Conversely, if the operator does not modify any of its operands, but needs only a representation of the object, it does not have to be a member function and often less confusing. This is the reason why binary operators are often implemented as friend functions such as + , *, -, etc..
35) What is the difference between class and structure? Ans: 1: By default, the members of structures are public while that for class is private 2: structures doesn’t provide something like data hiding which is provided by the classes 3: structures contains only data while class bind both data and member functions
36) What is virtual class and friend class? Ans: Friend classes are used when two or more classes are designed to work together and virtual base class aids in multiple inheritances.
37) Is there any way to write a class such that no class can be inherited from it. Please include code Ans: Simple, make all constructors of the class private.
38) Why can’t we overload the size of, :?, :: ., .* operators in c++ Ans: The restriction is for safety. For example, if we overload. An operator, then we can’t access member in the normal way for that we have to use ->.
39) What is the importance of const. pointer in the copy constructor? Ans: Because otherwise, you will pass the object to copy as an argument of copy constructor as pass by value which by definition creates a copy and so on… an infinite call chain.
Arun Gandham
Author
Hola peeps! A fitness freak, a lover of games, I catch a flick on the weekends and write for you about current trends.