C/C++ - Concepts & General Questions

  1. What is a stream?
    Stream is a sequence of bytes.
  2. What does mean int **p?
    1. Pointer to pointer to int
    2. Pointer to array of int
    3. int pointer to int pointer
    4. int of pointer to pointer
    1 or 2. It may either mean a single pointer to an int or a pointer to array of int[s].
  3. What is it implicit argument?
    The only implicit argument I found in C++ is this. I guess this is what the answer assumes. this is passed to member function call as an implicit argument of member function (you may see it in assembler)


  1. Where vtable is initialized?
    This type of question is supposed to get you out of the saddle. In constructor, of course.
  2. Question regarding constructor and destructor : What would be the output of the program1? Could you explain the role of virtual destructor ?
    This was a simple question to check your basic understanding:
    1. A Constructor
    2. B Constructor
    3. C Constructor
    4. C Destructor
    5. B Destructor
    6. A Destructor
    A virtual destructor ensures that, when delete is applied to a base class pointer or reference, it calls the destructor implemented in the derived class, if an implementation exists.
  3. What would be the output of the program2?
    • Step 1: A::f() (f() is called within class A)
    • Step 2: B::DO() ('a' downcasted to 'b')
    • Step 3: A::test() (because class C is a friend class of A and, hence, has an access to private members of the class A)
  4. What's wrong with the following code ?
    class A
    int i;
    int j;


    :j(0), i(j)
    In C++ the initialization of members is performed in order of their declaration. 'i' was declared before 'j'. Therefore, 'i' will be initialized first and the value of 'j' is undefined at that time.
  5. How does C++ copy objects if your program doesn't provide a copy constructor?
    If you do not supply a copy constructor, the compiler attempts to generate one. A compiler-generated copy constructor sets up a new object and performs a memberwise (not bitwise!!!) copy of the contents of the object to be copied. If base class or member constructors exist, they are called; otherwise, bitwise copying is performed.
  6. What's inappropriate in the following code:
    CMyObject *pobj = new CObject[128];
    char *pArray = new char[128];
    delete pArray;
    delete pobj;
    You should understand the difference between scalar and vector deleting of the objects. If you allocate memory for a vector of objects and then delete the pointer to the vector, only the destructor of the first element of the vector will be deallocated. To ensure all elements of the vector are being destroyed, you should use the following syntax:

    delete [] pobj; // must
    delete [] pArray; // should

    Strictly saying, for simple types such as char, int, etc. you don't have to use delete[], but it is highly recommended to use the same form delete[] for all vectors.
  7. What happens when the object is being destructed (or, in other words, what's the order of object destruction)?
    When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows:
    1. The class's destructor is called, and the body of the destructor function is executed.
    2. Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration. The optional member initialization list used in construction of these members does not affect the order of construction or destruction.
    3. Destructors for nonvirtual base classes are called in the reverse order of declaration.
    4. Destructors for virtual base classes are called in the reverse order of declaration.
  8. (Very important question - many people fail here despite this question is as stupid(as all others!!!) Mark which lines are wrong (you may be asked how references or/and pointers are initialized)?
    int a = 10;
    int *b = a;
    int *c = &a;
    int &d = a;
    int &e = &a;
    int &f = *c;
    One thing that you must remember as the word c++ itself is references are always initialized with value, while pointers are always initialized with address. Once you remember this simple rule, you'll be able to easily answer this type of question.
    int a = 10;
    // error cannot convert from int to int*: int *b = a;
    int *c = &a;
    int &d = a;
    // error cannot convert from int* to int&: int &e = &a;
    int &f = *c;
  9. Write all constructors for the following classes so that DoorWithLock class could be called with the constructor DoorWithLock(1,300,400,300), where 1,300,400,300 are the default parameters:
    class Door{ private: int m_Height, m_Width; }
    class Lock{ private: int m_Type; }
    class DoorWithLock{ private: Lock lock; int m_Owner; }
    This should go like this:
    class Lock
    Lock(int Type = 300)
    m_Type = Type;
    int m_Type;

    class DoorWithLock: public Door, public Lock
    DoorWithLock(int Owners = 1, int Type = 300, int Height = 400, int Width = 150)
    :Door(Height, Width), lock(Type), m_Owners(Owners)
    Lock lock;
    int m_Owners;
  10. What's wrong with the following code? Could you suggest alternative way of array's initialization?
    char *pArray = new char[256];
    for( int i = 0; i <>
    Nothing wrong really with this code. You may mention that 0 is not char and compiler may complain, that "cannot convert from int to char". However, most compiler would eat this initialization without problem whatsoever. You may mention that other ways of array initialization are using memset(pArray, 0, 256), ZeroMemory() (if we are talking about Windows) or stl's for_each() algorithm. You might want to mention also that in this particular case you would use stl::string rather than char* (but this really depends on context of the question)


  1. Can assignment operator be virtual?
    Yes, but it's not recommended. It is extremely bad and dangerous practice!


  1. What is the difference between a virtual function and a non-virtual function?
    Virtual attribute for a functions assumes that its body will be possibly overridden in the derived class. Non-virtual function is always called from the class where it is defined. You may also say that "virtual" functions implement polymorphism (by the way, it is highly recommended to put all you know about virtual and polymorphism in the answer. Do not follow blindly to all these answers.) Again, it is quite important that you demonstrate the understanding of the intent of virtual function to be overwritten in the derived class.
  2. What is the output of the program3?
    • 3
    • 2
    • 3
    • 4
  3. What is the output of the program4? Why?
    The answer in this particular case is B::foo(). If you would create an object of type A, A::foo() would be called.
  4. What does mean extern "C" int foo();
    1. Function foo() implemented in C
    2. Function foo() exported to C dll
    3. Function foo() is a global function in C++ program
    4. Function foo() uses C naming convention in C++ program?
    4. foo() uses C naming convention in C++ program.


  1. What does the following constant mean? const int f(const int &i) const
    Function that accepts "const int" argument (i.e. value of the argument cannot be changed), returning "const int" and cannot modify the object's members (last const)
  2. What is a const member function?
    Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. A constant member function cannot modify any data members or call any member functions that aren't constant.
  3. What is the difference between const and non-const parameter of a function?
    For simple types (int, char etc.) there is no difference. For parameters-pointers it means that the value it points to cannot be modified (however, you may move the pointer itself, since it will be only copy of the pointer of the original object.) For references it means values of the object cannot be modified. Parameter that is not const pointer involves a copy constructor, that is kind of waste for big objects)


  1. Why is it important to use reference during "catch" statement?
    "important" is inappropriate word, because it depends on the situation. One thing that might come to mind is that C++'s exception mechanism is able to catch exceptions of any type, for example a custom class. To avoid a copy of the exception object during exception twice, you may use a references. In this case the exception object is initialized to point to the actual thrown exception object. Exception is always thrown by value. Therefore, if you use by-value parameter in catch statement, you force the compiler to invoke the copy constructor twice.
  2. What's wrong with the following code ?
    Type& ClassA::FunctionX();
    Type1 obj;
    return obj;
    You cannot return the address of a local variable, because it will be destroyed when the function returns.
  3. What is wrong with the following version of the swap() function?
    void swap(int& x, int& y)
    x = y;
    y = x;
    It's not really a swap function, because the value of x will be hopelessly lost after the first assign.
  4. What is wrong with the following version of the swap() function?
    void swap(int x, int y)
    temp = x;
    x = y;
    y = x;
    The values of x and y will not be changed (they will be changed inside of swap function, but not for the outside world.
  5. What is the difference between returning by value and returning by reference?
    When you return the object by value, copy constructor is called, which is not the case when you return by reference (see item 22 of Scott Meyers.) But see item 23 for discussion when you don't have to pass by reference.

Static members

  1. What is the role of static member variables?
    Static member variables are the same value for all instances of the class.
  2. What is the role of static member functions?
    Static member functions are not really the members. The idea is that you may call the static member function from any other class, if you specify the base class name where the static member function was declared. Of course, static member function cannot change the members of the class.

C/C++ Interoperability

  1. How can C++ code call a function compiled by a C compiler?
    You should use extern "C" for functions, compiled by C compiler and called within a C++ class. You should do that to force the linker to resolve the function name (precisely, the mangling of the name) correctly.
  2. How can you create a C++ function that is callable from C-compiled code?
    What a perverted logic! Why would you need this?! Anyway, if you need this, you should know that only static or friend functions of the class may be called from C program. If you don't have static function, you should create a static wrapper around the member function. Then, declare the function with extern "C".
  3. What are the limitation when calling C++ functions from C-compiled code?
    See previous answer. Only static and friend functions might be called from C program.
  4. What is the difference between C's string and C++'s string?
    The major difference is that string in C is a char*, i.e. stream, while C++'s string is a class that works with streams.
  5. What is the difference between C and C++?
    Shortly speaking, C++ is an object-oriented language (well, kind of), which supports such OO terms as encapsulation, inheritance and polymorphism. C is a functional programming language, which has no meaning of object (here you may shine with you erudition, mentioning object-oriented C, which does know about objects)
  6. Could you use the following function in C: void foo(int i = 0; int j);
    No, you cannot use this signature in C, since default parameters (int i = 0) are defined only in C++.

Exception Handling

  1. What are the advantage and disadvantage of using exception handling?
    Disadvantage is a slight overhead imposed by implementing of exception handling mechanism. Advantage is "bullet-proof" program. With exception handling you have a mechanism which guarantee you control over program behavior despite the errors that might be in your program. With try-catch block you control not even given block of the program, but also all underlying function calls.
  2. Why might you need exception handling be used in the constructor when memory allocation is involved?
    Your first reaction should be: "Never use memory allocation in the constructor." Create a separate initialization function to do the job. You cannot return from the constructor and this is the reason you may have to use exception handling mechanism to process the memory allocation errors. You should clean up whatever objects and memory allocations you have made prior to throwing the exception, but throwing an exception from constructor may be tricky, because memory has already been allocated and there is no simple way to clean up the memory within the constructor.


  1. What are the advantage and disadvantage of using template functions?
    Template functions allow you to define the same behavior for different types.
  2. What are the advantages of templates in C++?
    Templates have several advantages.
    Firstly, they allow to avoid inappropriate multiple inheritance, where one of the inherited classes is just type to be managed.
    Secondly, they allow to inherit from "unknown" type, therefore creating "management" class for unknown type.
    Thirdly, templates allow to create "general" classes that is especially useful for all kind of type-safe collection classes.
    One good use is building framework classes that unite and hide several internal implementation classes (which can be non-template). This makes it easy for a beginner to use a big integrated complex functional class and still allows advanced users to rewrite portions of actual implementation.
    Drop me email if you think about more advantages. This is pretty open discussion.
  3. How many templates have you ever written?
    You may think I am kidding. No, this is one of the question I was actually asked at the interview. I was quite puzzled by this question. Say some numbers: 100, 1000. Number does not matter. What does matter in this case is your real knowledge of templates and you will either fail during further questions or succeed.
  4. Write a generic class, which is container of indexes and numbers, with function determining the minimal number from the numbers of the container.
    I guess you should write something like the program 5.
  5. What is the difference between class template and template class?
    Class templatea template used to generate template classes. A class template can be only a declaration, or it can be a definition of th e class.
    Template classan instance of a class template.


  1. What is the difference between list and vector?
    There are few differences:
    1. list and vector implement fundamentally different data structures.
    2. The major difference is the way of element access. Vector elements may accessed randomly while list elements must be accessed sequentially.
    3. Iterators are different as a result of the first item: list support bi-directional iterators while vector uses random access iterator.
    4. Some methods are difference (for example, only list supports merge and splice, adds push_front and pop_front etc.
  2. What is an iterator?
    Vague question, vague answer. You should ask the interviewer which iterator it means: as a general term, an STL object or a design pattern? Regardless of the answer, you should answer that iterator is an object that provides a sequential access to the elements of the other objects without knowing the internal structure of the controlled object.
  3. What is the difference between vector and array?
    Again, context is important. Vector is a one-dimensional array. It's also an STL class while array is a data type.
  4. What is the difference between erase() and remove() of std::list?
    This is from the collection of dumb questions. MSDN is there precisely for that! However, for the documentation purposes, remove() removes elements by value, while erase() uses iterator for the same purpose.
  5. What are the advantages and disadvantages of using a hash table?
    First, I would strongly suggest to open any data structures book and to refresh your knowledge about hash tables. The advantage of hash table is quick access to stored elements. Disadvantage is that there no universal function to resolve the hash conflict and each and every way (chaining, rehashing etc.) has advantages and disadvntages for various cases.
  6. What is stl::string?
    typedef basic_string string;
    The type describes a specialization of template class basic_string for elements of type char
  7. What are parameters of stl::basic_string's constructor? What is char_traits class?
    class itself, char_traits, allocator. char_traits class is templatized class of one char's characterstics.
  8. Which of the following containers do not belong to STL: queue, list, vector?
    All three belong to STL.
  9. Implement function equal from header file of STL
    As a matter of fact (I though originally it was a joke) you might be required to write _any_ function from algorithm collection (I guess way to go for a standard committee)
  10. What are advantages/disadvantages of applying binary search algorithm to array (vector)?


  1. What's the difference between aggregation and containment?
    It was quite interesting story, because I wrote the difference in terms of COM and the interviewer meant C++. The only problem that when he drew the question, it turned out that he hardly knows terminology himself. Trust me, in terms of C++ (to be precise in terms of UML) there is NO diference between aggregation and containment. Aggregation IS containment and containment IS aggregation. There is a difference, however, between aggregation and composition. This question should sound: "What's the difference between aggregation and composition in terms of UML?". Back to answer. The difference between aggregation and composition is life term of participating objects. Aggregated object can exist without container. Composited object is managed by it's container and cannot live without it. Interviewer would probably expect that you will say that composition implemented by creating object by value and aggregation implemented by creating object by reference (or pointer), but strictly saying it's not true. The true difference is who manages the life cycle of the aggregated object.


  1. If you have a union consisting of integer (4 bytes) and double (8 bytes) what would be minimal size allocated for that union?


  1. What do the functions seekg() and seekp() do?
    No comments, please. You don't have to know what are those function. As an registrar, I'll document here that seekp() finds the position of the internal pointer of output stream, while seekg() finds the position of the internal pointer of the input stream. Now who is about to tell me what kind of person gave such name to those functions?!


  1. Implement a solution to the following problem:
    int sum2(int n);
    // Returns the sum of the first n squares.
    // PRECONDITION: n > 0
    // EXAMPLE: sum2(10) returns 385
    int sum2(int n)
    static int sum = 0;
    sum = sum + n * n;
    return ( 1 >= n ) ? sum : sum2(n-1);
  2. How many internal nodes does a full binary tree of height n have?
    2^^n - 1
  3. Write a function that swaps the values of two integer variables without using any other temporary variable; the function should have the following prototype: void swap (int& x, int&y)
    void swap (int& x, int&y)
    x = y – x;
    y = y - x;
    x = y + x;
  4. What is the signature of printf() (or any other function)?
    Theoretically, this is an attempt to test you ability to concentrate on details. Practically, this is as stupid question as all others in similar tests. For records, the signature of printf() is int printf(char *format, ...) and return value is number of characters written to the output stream.
  5. What's wrong with the following program? Would would be returned from foo()?
    Quite a few things. Main() must start with lower case (C++ is case sensitive). Bad style. You would not want to accept a programmer who does such things :) int *z = &x++ is unlikely to pass the compilation and intention of the author is not clear. In either case, this code will return just garbage.
  6. What is the signature of printf()?
    int printf(char *format,...); Please, do not make comments! :)
  7. What's wrong with the following code fragment?
    int *foo(int x)
    int *p = x++;
    return p;
    Compiler will warn that "cannot convert from int to int*".
  8. What's the correct way to determing the size (number of elements) of an array?
    a) size(array)/size(*array)
    b) size(*array)/size(array)
    c) size(array)/sizeof(array)
    d) sizeof(array)/size(array)
    e) sizeof(array)/sizeof(*array)
    f) sizeof(*array)/sizeof(array)
    Honestly, none of them :) You should use sizeof(array)/sizeof(array[0]) to get it.

No comments: