Google

C C++ Technical Interview Questions and Tips

  1. Mutable keyword?
    1. keyword is the key to make exceptions to const
    2. mutable data member is allowed to change during a const member function
    3. mutable data member is never const even when it is a member of a const object
    4. a const member function may change a mutable member
  2. Something you can do in C but not in C++?C++ applications generally slower at runtime and compilation - input/output
  3. Difference between calloc and malloc?
    1. malloc: allocate s bytes
    2. calloc: allocate n times s bytes initialized to 0
  4. What will happen if I allocate memory using new & free memory using free? WRONG
  5. Difference between printf and sprintf?
  6. sprintf: a function that puts together a string, output goes to an array of char instead of stdout
    printf: prints to stdout
  7. map in STL?
    1. used to store key - value pairs, value retrieved using the key
    2. store data indexed by keys of any type desire instead of integers as with arrays
    3. maps are fast 0(log(n)) insertion and lookup time
    4. std::map<key_type, data_type>EX:Std::map<string, char> grade_list //grade_list["john"] = b
  8. When will we use multiple inheritance?
    1. use it judiciously class
    2. when MI enters the design scope it becomes possible to inherit the same name (function/typedef) from more than one base class == ambiguity
    3. C++first identifies the function thats the best match for the call
    4. C++resolves calls to overload before accessibility, therefore the accessibility of Elec_Gadget() checkout is never evaluated because both are good matches == ERROR
    5. resolve ambiguity mp.Borrowable_Item::checkOut(); mp.Elec_Gadget::checkOut(); //error because trying to access private
    6. deadly MI diamond: anytime you have an inheritance hierarchy w/ more than one path between a base class and a derived classEX:FileInput File Output FileIOFile//File and IOFile both have paths through InputFile and OutputFile
  9. Multithreading - C++does not have a notion of multithreading, no notion of concurrency
  10. Why is the pre-increment operator faster than the post-increment operator? pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types
  11. What is a hash and what would you use it for?
  12. What is a dot product and what is a cross product - what would you use them for?
  13. What is 2 ^ 101?

Most FAQ C C++ Satyam Google

  1. Different types of polymorphism
    1. types related by inheritance as polymorphic types because we can use many forms of a derived or base type interchangeably
    2. only applies to ref or ptr to types related by inheritance.
    3. Inheritance - lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different
    4. derived classes
      1. can use w/o change those operations that dont depend on the specifics of the derived type
      2. redefine those member functions that do depend on its type
      3. derived class may define additional members beyond those it inherits from its base class.
    5. Dynamic Binding - lets us write programs that use objects of any type in an inheritance hierarchy w/o caring about the objects specific types
    6. happens when a virtual function is called through a reference ptr to a base class
    7. The fact that a reference or ptr might refer to either a base or derived class object is the key to dynamic binding
    8. calls to virtual functions made though a reference/ptr resolved @ runtime
    9. the function that is called is the one defined by the actual type of the object to which ref/ptr refers
  2. How to implement virtual functions in C - keep function pointers in function and use those function ptrs to perform the operation
  3. What are the different type of Storage classes?
    1. automatic storage: stack memory - static storage: for namespace scope objects and local statics
    2. free store: or heap for dynamically allocated objects == design patterns
  4. What is a namespace?
    1. every name defined in a global scope must be unique w/in that scope
    2. name collisions: same name used in our own code or code supplied to us by indie producers == namespace pollution
    3. name clashing - namespace provides controlled mechanism for preventing name collisions
    4. allows us to group a set of global classes/obj/funcs
    5. in order to access variables from outside namespace have to use scope :: operator
    6. using namespace serves to assoc the present nesting level with a certain namespace so that objectand funcs of that namespace can be accessible directly as if they were defined in the global scope
  5. Types of STL containers - containers are objects that store other objects and that has methods for accessing its elements - has iterator - vector
  6. Difference between vector and array - -array: data structure used dto store a group of objects of the same type sequentially in memory - vector: container class from STL - holds objects of various types - resize, shrinks grows as elements added - bugs such as accessing out of bounds of an array are avoided
  7. Write a program that will delete itself after execution. Int main(int argc, char **argv) { remove(argv[0]);return 0;}
  8. What are inline functions?
    1. treated like macro definitions by C++ compiler
    2. meant to be used if there's a need to repetitively execute a small block if code which is smaller
    3. always evaluates every argument once
    4. defined in header file
    5. avoids function call overload because calling a function is slower than evaluating the equivalent expression
    6. it's a request to the compiler, the compiler can ignore the request
  9. What is strstream? defines classes that support iostreams, array of char obj
  10. Passing by ptr/val/refArg?
    1. passing by val/refvoid c::f(int arg) – by value arg is a new int existing only in function. Its initial value is copied from i. modifications to arg wont affect the I in the main function
    2. void c::f(const int arg) – by value (i.e. copied) the const keyword means that arg cant be changed, but even if it could it wouldnt affect the I in the main function
    3. void c::f(int& arg) - -by reference, arg is an alias for I. no copying is done. More efficient than methods that use copy. Change in arg == change in I in the calling function
    4. void c::f(const int& arg) - -by reference, int provided in main call cant be changed, read only. Combines safety with efficacy.
    5. void c::f(const int& arg) const – like previous but final const that in addition the function f cant change member variables of cArg passing using pointers
    6. void c::f(int *arg) – by reference changing *arg will change the I in the calling function
    7. void c::f(const int *arg) – by reference but this time the I int in the main function cant be changed – read only
    8. void c::f(int * const arg) – by reference the pointer arg cant be changed but what it points to (namely I of the calling function) can
    9. void c::f(const int * const arg) by reference the pointer arg cant be changed neither can what it points to

C C++ overloading and overriding Most Faq

  1. Difference between overloading and overriding?
    1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
    2. main() cannot be overloaded
    3. notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
    4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
    5. Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
    6. the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
    7. writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
    8. all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature
  2. Virtual
    1. single most important feature of C++ BUT virtual costs
    2. allows derived classes to replace the implementation provided by the base class
    3. without virtual functions C++ wouldnt be object oriented
    4. Programming with classes but w/o dynamic binding == object based not OO
    5. dynamic binding can improve reuse by letting old code call new code
    6. functions defined as virtual are ones that the base expects its derived classes to redefine
    7. virtual precedes return type of a function
    8. virtual keyword appears only on the member function declaration inside the class
    9. virtual keyword may not be used on a function definition that appears outside the class body
    10. default member functions are nonvirtual
  3. Dynamic Binding
    1. delaying until runtime the selection of which function to run
    2. refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
    3. applies only to functions declared as virtual when called thru reference or ptr
    4. in C++ dynamic binding happens when a virtual function is called through a reference (|| ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers
  4. Explain the need for a virtual destructor
    1. destructor for the base parts are invoked automatically
    2. we might delete a ptr to the base type that actually points to a derived object
    3. if we delete a ptr to base then the base class destructor is run and the members of the base class are cleared up. If the objectis a derived type then the behavior is undefined
    4. to ensure that the proper destructor is run the destructor must be virtual in the base class
    5. virtual destructor needed if base pointer that points to a derived object is ever deleted (even if it doesnt do any work)
  5. Rule of 3
    1. if a class needs a destructor, it will also need an assignment operator and copy constructor
    2. compiler always synthesizes a destructor for us
    3. destroys each nonstatic member in the reverse order from that in which the object was created
    4. it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
    5. make destructor virtual if your class has any virtual functions
  6. Why do you need a virtual destructor when someone says delete using a Base ptr thats pointing @ a derived object? - when you say delete p and the class of p has a virtual destructor the destructor that gets invoked is the one assoc with the type of the object*p not necessarily the one assoc with the type of the pointer == GOOD

C structure and C++ structure interview questions

This is not really a set of interview questions, a reader sent TechInterviews.com what looks like a copy of his notes from C++ class that describes various tricks and code for C++.

  1. What is the output of printf("%d")?
    1. %d helps to read integer data type of a given variable
    2. when we write ("%d", X) compiler will print the value of x assumed in the main
    3. but nothing after ("%d") so the output will be garbage
    4. printf is an overload function doesnt check consistency of the arg list – segmentation fault
  2. What will happen if I say delete this? - destructor executed, but memory will not be freed (other than work done by destructor). If we have class Test and method Destroy { delete this } the destructor for Test will execute, if we have Test *var = new Test()
    1. pointer var will still be valid
    2. object created by new exists until explicitly destroyed by delete
    3. space it occupied can be reused by new
    4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
    5. delete = delete objects
    6. delete[] – delete array
    7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
    8. if a destructor has been defined fir a class delete invokes that desructor
  3. Difference between C structure and C++ structure - C++ places greater emphasis on type checking, compiler can diagnose every diff between C and C++
    1. structures are a way of storing many different values in variables of potentially diff types under under the same name
    2. classes and structures make program modular, easier to modify make things compact
    3. useful when a lot of data needs to be grouped together
    4. struct Tag {…}struct example {Int x;}example ex; ex.x = 33; //accessing variable of structure
    5. members of a struct in C are by default public, in C++ private
    6. unions like structs except they share memory – allocates largest data type in memory - like a giant storage: store one small OR one large but never both @ the same time
    7. pointers can point to struct:
    8. C++ can use class instead of struct (almost the same thing) - difference: C++ classes can include functions as members
    9. members can be declared as: private: members of a class are accessible only from other members of their same class; protected: members are accessible from members of their same class and friend classes and also members of their derived classes; public: members are accessible from anywhere the class is visible
    10. structs usually used for data only structures, classes for classes that have procedures and member functions
    11. use private because in large projects important that values not be modified in an unexpected way from the POV of the object
    12. advantage of class declare several diff objects from it, each object of Rect has its own variable x, y AND its own functions
    13. concept of OO programming: data and functions are properties of the object instead of the usual view of objects as function parameters in structured programming
  4. Difference between assignment operator and copy constructor - -assignment operator = assigning a variable to a value - copy constructor
    1. constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
    2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
    3. copy constructor takes care of initialization by an object of the same type x
    4. for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
    5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
    6. if a class needs a copy constructor it will also need an assignment operator
    7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
    8. assignment is like deconstruction followed by construction
    9. assignment operator assigns a value to a already existing object
    10. copy constructor creates a new object by copying an existing one
    11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
    12. the assignment operator makes an already existing object into a copy of an existing one.
    13. copy constructor always creates a new object, assignment never does

C++ interview questions TechInterviews Satyam

C++ interview questions

This set of C++ interview questions was sent to TechInterviews from Australia:

  1. What is the difference between an ARRAY and a LIST?
  2. What is faster : access the element in an ARRAY or in a LIST?
  3. Define a constructor - what it is and how it might be called (2 methods).
  4. Describe PRIVATE, PROTECTED and PUBLIC – the differences and give examples.
  5. What is a COPY CONSTRUCTOR and when is it called (this is a frequent question !)?
  6. Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and SQUARE.
  7. What is the word you will use when defining a function in base class to allow this function to be a polimorphic function?
  8. What are 2 ways of exporting a function from a DLL?
  9. You have two pairs: new() and delete() and another pair : alloc() and free(). Explain differences between eg. new() and malloc()
  10. What is a callback function. Explain in C and C++ and WIN API environment.
  11. (From WINDOWS API area): what is LPARAM and WPARAM?

C++ recent Interview Papers

C++ developer interview

  1. Will the following program execute?void main()
    {
    void *vptr = (void *) malloc(sizeof(void));
    vptr++;
    }

  2. How about this one?
    void main()
    {
    char *cptr = 0?2000;
    long *lptr = 0?2000;
    cptr++;
    lptr++;
    printf(" %x %x", cptr, lptr);
    }
    Will it execute or not?
  3. When the processor wakes up after power on, it goes to a particular memory location. What is that memory location called?
  4. What is the difference between Mutex and Binary semaphore?
  5. Write a program to set 2nd bit in a 32 bit register with memory location 0×2000?

Latest C C++ interview questions Papers

  • To which numbering system can the binary number 1101100100111100 be easily converted to?
  • Which bit wise operator is suitable for checking whether a particular bit is on or off?
  • Which bit wise operator is suitable for turning off a particular bit in a number?
  • Which bit wise operator is suitable for putting on a particular bit in a number?
  • Which bit wise operator is suitable for checking whether a particular bit is on or off?
  • Which one is equivalent to multiplying by 2?
    • Left shifting a number by 1
    • Left shifting an unsigned int or char by 1?
  • Write a program to compare two strings without using the strcmp() function.
  • Write a program to concatenate two strings.
  • Write a program to interchange 2 variables without using the third one.
  • Write programs for String Reversal. The same for Palindrome check.
  • Write a program to find the Factorial of a number.
  • Write a program to generate the Fibonacci Series?
  • Write a program which employs Recursion?
  • Write a program which uses command line arguments.
  • Write a program which uses functions like strcmp(), strcpy(), etc.
  • What are the advantages of using typedef in a program?
  • How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
  • How can you increase the size of a dynamically allocated array?
  • How can you increase the size of a statically allocated array?
  • When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
  • Which function should be used to free the memory allocated by calloc()?
  • How much maximum can you allocate in a single call to malloc()?
  • Can you dynamically allocate arrays in expanded memory?
  • What is object file? How can you access object file?
  • Which header file should you include if you are to develop a function which can accept variable number of arguments?
  • Can you write a function similar to printf()?
  • How can a called function determine the number of arguments that have been passed to it?
  • Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
  • How do you declare the following:
    • An array of three pointers to chars
    • An array of three char pointers
    • A pointer to array of three chars
    • A pointer to function which receives an int pointer and returns a float pointer
    • A pointer to a function which receives nothing and returns nothing
  • What do the functions atoi(), itoa() and gcvt() do?
  • Does there exist any other function which can be used to convert an integer or a float to a string?
  • How would you use qsort() function to sort an array of structures?
  • How would you use qsort() function to sort the name stored in an array of pointers to string?
  • How would you use bsearch() function to search a name stored in array of pointers to string?
  • How would you use the functions sin(), pow(), sqrt()?
  • How would you use the functions memcpy(), memset(), memmove()?
  • How would you use the functions fseek(), freed(), fwrite() and ftell()?
  • How would you obtain the current time and difference between two times?
  • How would you use the functions randomize() and random()?
  • How would you implement a substr() function that extracts a sub string from a given string?
  • What is the difference between the functions rand(), random(), srand() and randomize()?
  • What is the difference between the functions memmove() and memcpy()?
  • How do you print a string on the printer?
  • Can you use the function fprintf() to display the output on the screen?
  • Gautam Pagedar adds this question: What is a linklist and why do we use it when we have arrays? - I feel the correct answer should be linklist is used in cases where you don't know the memory required to store a data structure and need to allocate is dynamically on demand.
  • How do you detect a loop in linked list?
  • Sunil asks: What is the difference between main() in C and main() in C++?
  • ajz at his interviews asks what will be printed out when the following code is executed:

    main()
    {
    printf("%x",-1<<4);
    }

Latest C interview questions

A frequent reader of this site sent this in. No answers, but a nice set of questions. Consider getting Kernighan and Ritchie title if you find many things puzzling here.

  1. What does static variable mean?
  2. What is a pointer?
  3. What is a structure?
  4. What are the differences between structures and arrays?
  5. In header files whether functions are declared or defined?
  6. What are the differences between malloc() and calloc()?
  7. What are macros? What are the advantages and disadvantages?
  8. Difference between pass by reference and pass by value?
  9. What is static identifier?
  10. Where are the auto variables stored?
  11. Where does global, static, local, register variables, free memory and C Program instructions get stored?
  12. Difference between arrays and linked list?
  13. What are enumerations?
  14. Describe about storage allocation and scope of global, extern, static, local and register variables?
  15. What are register variables? What are the advantage of using register variables?
  16. What is the use of typedef?
  17. Can we specify variable field width in a scanf() format string? If possible how?
  18. Out of fgets() and gets() which function is safe to use and why?
  19. Difference between strdup and strcpy?
  20. What is recursion?
  21. Differentiate between a for loop and a while loop? What are it uses?
  22. What are the different storage classes in C?
  23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
  24. What is difference between Structure and Unions?
  25. What the advantages of using Unions?
  26. What are the advantages of using pointers in a program?
  27. What is the difference between Strings and Arrays?
  28. In a header file whether functions are declared or defined?
  29. What is a far pointer? where we use it?
  30. How will you declare an array of three function pointers where each function receives two ints and returns a float?
  31. What is a NULL Pointer? Whether it is same as an uninitialized pointer?
  32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
  33. What does the error 'Null Pointer Assignment' mean and what causes this error?
  34. What is near, far and huge pointers? How many bytes are occupied by them?
  35. How would you obtain segment and offset addresses from a far address of a memory location?
  36. Are the expressions arr and *arr same for an array of integers?
  37. Does mentioning the array name gives the base address in all the contexts?
  38. Explain one method to process an entire string as one unit?
  39. What is the similarity between a Structure, Union and enumeration?
  40. Can a Structure contain a Pointer to itself?
  41. How can we check whether the contents of two structure variables are same or not?
  42. How are Structure passing and returning implemented by the complier?
  43. How can we read/write Structures from/to data files?
  44. What is the difference between an enumeration and a set of pre-processor # defines?
  45. What do the 'c' and 'v' in argc and argv stand for?
  46. Are the variables argc and argv are local to main?
  47. What is the maximum combined length of command line arguments including the space between adjacent arguments?
  48. If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?
  49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
  50. What are bit fields? What is the use of bit fields in a Structure declaration?

C interview questions

What does static variable mean?
What is a pointer?
What is a structure?
What are the differences between structures and arrays?
In header files whether functions are declared or defined?
What are the differences between malloc() and calloc()?
What are macros? What are the advantages and disadvantages?
Difference between pass by reference and pass by value?
What is static identifier?
Where are the auto variables stored?