Vous êtes sur la page 1sur 12

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

Answer :A memory leak can be avoided by making sure that whatever memory has bee n dynamically allocated will be cleared after the use of the same. for example i nt main() { char *myCharData[20]; for (int nLoop =0;nLoop < 20; ++nLoop) { myCha rData[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 o utput? Answer :write this program and save it as pro.c....run....it will show the progr am 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); p rintf("%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 iVar 2 = 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 shou ld 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 occu rrence 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 st oring 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. Esse ntially the compiler uses namespace to distinguish between local and global stat ic 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 i s 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. Macr os 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 pr actice 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 dynam ically allocated memory is lost to the program. Char * p; p= new char[10000]; .. ... p= new char[5000]; Initially, 10000 bytes are dynamically allocated & the th e address of those bytes is stored in p. later 5000 bytes are dynamically alloca ted & the address is stored in p. However, the original 10000 bytesve not been re turned to the system using delete [] operator. Memory leak actually depends on t he nature of the program. Question: class A() { }; int main() {

A a; } Whether there will be a default contructor provided by the compiler in ab ove case ? Answer :yes, if the designer of the class donot define any constructor in the cl ass. 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 th ere is no any strong reason for not using virtual destructor....like...One class having two char variable...........so its size is two byte........if u use vir tual destructor its size will be 6 bytes....4 byte for virtual ptr....Now if th is 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 st atement Answer :we cant make object of abstract class becoz, in the vtable the vtable en try for the abstract class functions will be NULL, which ever are defined as pur e virtual functions... even if there is a single pure virtual function in the cl ass 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 si ngle 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 thi s 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 obj ect is not initialized to any value so the default constructor will be called wh ich 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 a ssign a value to this data member from a const member function. SEE FOLLOWING CO DE :******************************************** 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 w ill 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 generat e binary file. High level language programming code -low level programming codehex codebinary 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 s plitter from binary to assembly language (low level language)/ Converter type de vices available, they use them for secret national purpose. Question: Explain "passing by value", "passing by pointer" and "passing by refer ence" 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 ca lling

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 a ble array, where you access to the elements in it through an index. Array List its part of the Java Collection Framework, and has been added with version 1.2, while Vector its 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 its a synchronized object, while Array List its not. While the iterator that are returned by both classes are fail-fast (they cleanl y thrown a ConcurrentModificationException when the original object has been mod ified), the Enumeration returned by Vector are not. Unless you have strong reaso n 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 mu ltiset 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 functions return va lue, a temporary copy of that object is made. Assignment operator is called when ever 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 opposit e way of their construction. If virtual keyword is not added before base class d estructor 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 twi ce, 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. S ince this is the language behavior, there is no way to prevent the destructor fr om being called twice. Please refrain from forcibly calling a destructor or usin g 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 implement ation, which takes start and end iterators of STL container on which algo is goi ng to work. Question: How can you force instantiation of a template?

Answer: you can instantiate a template in two ways. 1. Implicit instantiation an d 2. Explicit Instantion. implicit instatanitioan can be done by the following w ays: template <class T> class A { public: A(){} ~A(){} void x(); void z(); }; vo id main() { A<int> ai; A<float> af; } External Instantion can be done the follow ing 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 in voked 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 i t. Where as the new operator also initializes it properly by calling the constru ctor. Question: What is the Basic nature of "cin" and "cout" and what concept or princ iple we are using on those two? Answer: Basically "cin and cout" are INSTANCES of istream and ostream classes re spectively. And the concept which is used on cin and cout is operator overloadin g. Extraction and Insertion operators are overloaded for input and ouput operati ons.

Question: What are virtual functions? Answer: C++ virtual function is a member function of a class, whose functionalit y 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 f unctionality 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 no t 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 Conv ersely, if the operator does not modify any of its operands, but needs only a re presentation of the object, it does not have to be a member function and often l ess 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 doesnt provide something like data hiding which is pro vided 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 to gether 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 cant we overload the sizeof, :?, :: ., .* operators in c++ Answer: The restriction is for safety. For example if we overload. Operator then we cant 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 cop y constructor as pass by value which by definition creates a copy and so on... a n infinite call chain

Vous aimerez peut-être aussi