Você está na página 1de 11

C++ INTERVIEW QUESTIONS

Question: What is a memory leak? How can we avoid it?


Answer :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;

Question: How do you write a program which produces its own source code as its
output?

Answer :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<stdio.h>
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);
}
}

Question: What are the things contains in .obj file ? ( compiled result of .cpp file )
Answer :C++ .obj file holds code and data suitable for linking with other object files to
create an executable or a shared object file.

Question :What is difference between followin intialization.

int iVar1;
int iVar2 = int();

and which one of two should we prefer always and why?

Answer :In first case a variable will be create in memeory with the default base type
value (depending upon compiler 2 compiler) bcoz it is not initialized. in second case the
variable will be created in the memory with the value retuned by the function int() (if int
is a user define function) the second statement should have been int *i = new int();

Question :What is the difference between Object and Instance?

Answer :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.

Question: 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).

Answer: C++ uses name mangling when storing both local and global static varibales at
the same place. The local static variables have function name and the global variables
will have file name. Essentially the compiler uses namespace to distinguish between local
and global static variables.
Question :what is the difference betwen wait() and delay()?

Answer :Wait() and delay() works same but works on different platforms. Wait(2) will
wait processing fro 2 second on Linux/Unix while delay(2000) with wait for 2 second but
on DOS or Windows.

so wait(2) on linux == delay(2000) on DOS

Delay() is under <dos.h> while one can directly use wait in his/her program.

Question :Why always array starts with index 0

Answer :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.

Question: Can main() be overridden

Answer : 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

Question :What is the difference between macro and inline()?

Answer :1. Inline follows strict parameter type checking, macros do not.

2. Macros are always expanded by preprocessor, whereas compiler may or may not
replace the inline definitions.

Question: How can double dimensional arrays be dynamically initialized in C++?


Answer :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

Question: Can destructor be private?

Answer: Yes destructors can be private. But according to Standard Programming practice
it is not advisable to have destructors to be private.

Question: what is memory leaking in c++ ?

Answer: 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 the 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 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’ve not been returned to the system using delete [] operator.

Memory leak actually depends on the nature of the program.

Question:

class A()
{
};

int main()
{
A a;
}

Whether there will be a default contructor provided by the compiler in above case ?
Answer :yes, if the designer of the class donot define any constructor in the class. then
the compiler provides the default constructor in the class.

Question: what is the use of virtual destructor?

Answer :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 byte for virtual ptr....Now if this class have 1 millions objects...so 4 magabyte
memory will be lost...where all ptr do the same thing.....

Question: Why cant one make an object of abstract class?Give compiler view of
statement

Answer :we cant make object of abstract class becoz, in the vtable the vtable entry for
the abstract class functions will be NULL, which ever are defined as pure virtual
functions...

even if there is a single pure virtual function in the class the class becomes as 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.

Question: In c++ have a default constructor?


Answer: 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.

Question: Have you heard of "mutable" keyword?


Answer :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
}

Question: What is "strstream”?

Answer: Class that reads and writes to an array in memory

Question: Can we generate a C++ source code from the binary file?

Answer: Technically this is possible, but in my knowledge their no such software


available yet. Why this is possible? In program flow we do like this to generate 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. 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 secret
national purpose.

Question: Explain "passing by value", "passing by pointer" and "passing by


reference"

Answer: There is major difference between these three are when we want to avoid
making the copy of variable and we want to change value of actual argument on calling
function. There are we use passing by pointer, passing the reference. We can not perform
arithmetic operation on reference.

Question: Difference between "vector" and "array"?

Answer: Vector and Array List are very similar. Both of them represent a 'grow able
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 are returned by both classes are fail-fast (they cleanly thrown a
ConcurrentModificationException when the original object has been modified), the
Enumeration returned by Vector are not.
Unless you have strong reason to use a Vector, the suggestion is to use the Array List

Question: What are the types of STL containers?

Answer: deque
hash_map
hash_multimap
hash_multiset
hash_set
list
map
multimap
multiset
set
vector

Question:Difference between a "assignment operator" and a "copy constructor"

Answer :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.

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
Question: Can we have "Virtual Constructors"?

Answer: No, we cannot have virtual constructors. But if the need arises, we can simulate
the implementation of virtual constructor by calling a Init method from the constructor
which, should be a virtual function.

Question: Explain the need for "Virtual Destructor".


Answer: In case of inheritance, objects should be destructed exactly the opposite way of
their construction. If 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.

Question: What will happen if I say delete this


Answer: if you say "delete this", you are effectively calling the destructor twice, which
could well be a disaster if your class uses 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 clause like this.

Question: What is the output of printf ("%d")


Answer :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

Question: # what is an algorithm (in terms of the STL/C++ standard library)?


Answer: 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.

Question: How can you force instantiation of a template?


Answer: 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 T>

class A

public:

A(){}

~A(){}

void x();

void z();

};

void main()

A<int> ai;

A<float> af;

External Instantion can be done the following way:

int main()

template class A<int>;

template class A<float>;

Question: What is the difference between operator new and the new operator?
Answer: 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. Where as the new operator
also initializes it properly by calling the constructor.

Question: What is the Basic nature of "cin" and "cout" and what concept or
principle we are using on those two?

Answer: 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 ouput operations.

Question: What are virtual functions?


Answer: C++ virtual function is a member function of a class, whose functionality can be
over-ridden 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

Question: We can overload assignment operator as a normal function.But we can


not overload assignment operator as friend function why?
Answer :If the operation modifies the state of the class object, it operates on, it must be a
member function, not a friend fucntionThus 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..

Question: What is the difference between class and structure?


Answer: 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
Question: What is virtual class and friend class?
Answer: Friend classes are used when two or more classes are designed to work together
and virtual base class aids in multiple inheritance.

Question: Is there any way to write a class such that no class can be inherited from
it. Please include code

Answer: Simple, make all constructors of the class private.

Question: Why can’t we overload the sizeof, :?, :: ., .* operators in c++

Answer: The restriction is for safety. For example if we overload. Operator then we can’t
access member in normal way for that we have to use ->.

Question :What is importance of const. pointer in copy constructor?

Answer :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

Você também pode gostar