0% found this document useful (0 votes)
39 views12 pages

C Interview Questions

Memory leak can be avoided by making sure that whatever memory has been dynamically allocated wi ll be cleared after the use of the same..obj file ho lds code and data suitable for linking with other object files to create an exec utable or a shared object file.

Uploaded by

crennydane
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views12 pages

C Interview Questions

Memory leak can be avoided by making sure that whatever memory has been dynamically allocated wi ll be cleared after the use of the same..obj file ho lds code and data suitable for linking with other object files to create an exec utable or a shared object file.

Uploaded by

crennydane
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

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 wi ll be cleared after the use of the same. for example int main() { char *myCharDa ta[20]; for (int nLoop =0;nLoop < 20; ++nLoop) { myCharData[nLoop ] = new char[2 56]; strcpy(myCharData[nLoop],"SABITH"); ...... } ........................ /*Som e manipulations here using myCharData*/ /*Now here we have to clear the data. Th e place can vary according to ur program. This being a simple program,u can clea r 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 sour ce 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.tx t","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 c ontains in .obj file ? ( compiled result of .cpp file ) Answer :C++ .obj file ho lds code and data suitable for linking with other object files to create an exec utable or a shared object file. Question :What is difference between followin in tialization. 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 seco nd statement should have been int *i = new int(); Question :What is the differen ce 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 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 d elay() 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> w hile 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 b egin) 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 mus t 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 onl y one main function. In c++, main is not a member of any class. There is no chan ce of overriding Question :What is the difference between macro and inline()? Answer :1. Inline f ollows strict parameter type checking, macros do not. 2. Macros are always expan ded by preprocessor, whereas compiler may or may not replace the inline definiti ons. Question: How can double dimensional arrays be dynamically initialized in C++? A nswer :example of how to dynamically initialize double dimensional arrays: int n um[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 destruct ors 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 o r handled, they can lead to memory leaks & corrupts Data Structures. A memory le ak 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, 1000 0 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. Howe ver, the original 10000 bytes ve not been returned to the system using delete [] ope rator. 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 ab ove case ? Answer :yes, if the designer of the class donot define any constructo r 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 fo r 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 objec ts...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 v table entry for the abstract class functions will be NULL, which ever are define d as pure virtual functions... even if there is a single pure virtual function i n 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 functio n 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 cre ate 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 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 fr om the binary file? Answer: Technically this is possible, but in my knowledge th eir 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 lev el programming code- hex codebinary code. How we can do reverse can be illustrat ed 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 an d decode this. Same technique can be used. Some secret mission defense org. I he ard 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 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 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 Collect ion 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 ret rofitted 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 ConcurrentModifica tionException when the original object has been modified), the Enumeration retur ned by Vector are not. Unless you have strong reason to use a Vector, the sugges tion is to use the Array List Question: What are the types of STL containers? Answer: deque hash_map hash_mult imap hash_multiset hash_set list map multimap multiset set vector Question:Difference between a "assignment operator" and a "copy constructor" Ans wer :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 wheneve r you assign to an object. Assignment operator must check to see if the right-ha nd side of the assignment operator is the object itself. It executes only the tw o 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 vir tual 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 inherita nce, 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 disast er if your class uses heap. The destructor will be called when you say delete this 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 refrai n from forcibly calling a destructor or using clause like this. Question: What is the output of printf ("%d") Answer :Usually the output value c annot be predicted. It will not give any error. It will print a garbage value. B ut 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)? Ans wer: Algorithm in STL consist different searching and sorting algos implementati on, 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?

and

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 principle we are using on those two? Answer: Basically "cin and cout" are INSTA NCES 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 f unction of a class, whose functionality can be over-ridden in its derived classe s. C++ virtual function is, * A member function of a class * Declared with virtu al keyword * usually has a different functionality in the derived class * A func tion 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 func tion, not a friend fucntionThus all operator such as =, *=, +=, etc are naturall y defined as member functions not friend functions Conversely, if the operator d oes not modify any of its operands, but needs only a representation of the objec t, it does not have to be a member function and often less confusing. This is th e 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 defau lt, the members of structures are public while that for class is private 2: stru ctures doesn't provide something like data hiding which is provided by the class es 3: structures contains only data while class bind both data and member functi ons

Question: What is virtual class and friend class? Answer: Friend classes are use d 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: Th e restriction is for safety. For example if we overload. Operator then we can t acce ss member in normal way for that we have to use ->. Question :What is importance of const. pointer in copy constructor? Answer :Beca use otherwise you will pass the object to copy as an argument of copy constructo r as pass by value which by definition creates a copy and so on... an infinite c all chain

You might also like