CppInterviewQuestions
From Epowiki
Contents |
Pre-interview Questions
These are questions to ask in a phone interview. The idea is to qualify a person before bringing them in for a face-to-face session.
- What is a virtual method? A pure virtual method? When would you use/not use a virtual destructor?
-
What is the difference between a pointer and a reference?
A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized. </P>
-
What is the difference between new/delete and malloc/free?
Malloc/free do not know about constructors and destructors. New and delete create and destroy objects, while malloc and free allocate and deallocate memory. </P>
- What does const mean?
- What methods should every c++ class define and why?
- What does main return?
- Explain what the header for a simple class looks like.
- How do you handle failure in a constructor? According to Bjarne Stroustup, designer of the C++ language, you handle failures in a constructor by throwing an exception. See here for more details, including a link to his document on exception safety and the standard library: http://www.arkestra.demon.co.uk/errors_cpp.html#acquire_resources_in_constructors
Junior Questions
-
What is the difference between C and C++? Would you prefer to use one over the other?
C is based on structured programming whereas C++ supports the object-oriented programming paradigm. Due to the advantages inherent in object-oriented programs such as modularity and reuse, C++ is preferred. However almost anything that can be built using C++ can also be built using C.
-
Explain operator precendence.
Operator precedence is the order in which operators are evaluated in a compound expression. For example, what is the result of the following expression? <P> 6 + 3 * 4 / 2 + 2
Here is a compound expression with an insidious error.
while ( ch = nextChar() != '\0' )
The programmer's intention is to assign ch to the next character then test that character to see whether it is null. Since the inequality operator has higher precendence than the assignment operator, the real result is that the next character is compared to null and ch is assigned the boolean result of the test (i.e. 0 or 1). </P>
-
What are the access privileges in C++? What is the default access level?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.
-
What is data encapsulation?
Data Encapsulation is also known as data hiding. The most important advantage of encapsulation is that it lets the programmer create an object and then provide an interface to the object that other objects can use to call the methods provided by the object. The programmer can change the internal workings of an object but this transparent to other interfacing programs as long as the interface remains unchanged.
-
What is inheritance?
Inheritance is a mechanism through which a subclass inherits the properties and behavior of its superclass; the subclass has a ISA relationship with the superclass. For example Vehicle can be a superclass and Car can be a subclass derived from Vehicle. In this case a Car ISA Vehicle. The superclass 'is not a' subclass as the subclass is more specialized and may contain additional members as compared to the superclass. The greatest advantage of inheritance is that it promotes generic design and code reuse.
-
What is multiple inheritance? What are its advantages and disadvantages?
Multiple Inheritance is the process whereby a sub-class can be derived from more than one super class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion when two base classes implement a method with the same name.
-
What is polymorphism?
Polymorphism refers to the ability to have more than one method with the same signature in an inheritance hierarchy. The correct method is invoked at run-time based on the context (object) on which the method is invoked. Polymorphism allows for a generic use of method names while providing specialized implementations for them.
-
What do the keyword static and const signify?
When a class member is declared to be of a static type, it means that the member is not an instance variable but a class variable. Such a member is accessed using Classname.Membername (as opposed to Object.Membername). Const is a keyword used in C++ to specify that an object's value cannot be changed.
-
What is a static member of a class?
Static data members exist once for the entire class, as opposed to non-static data members, which exist individually in each instance of a class.
-
How do you access the static member of a class?
<ClassName>::<StaticMemberName>. </P>
-
What feature of C++ would you use if you wanted to design a member function that guarantees to leave this object unchanged?
It is const as in:
int MyFunc (int test) const; -
What is the difference between const char *myPointer; and char *const myPointer;?
const char *myPointer; is a non-constant pointer to constant data; while char *const myPointer; is a constant pointer to non-constant data. </P>
-
How is memory allocated/deallocated in C? How about C++?
Memory is allocated in C using malloc() and freed using free(). In C++ the new() operator is used to allocate memory to an object and the delete() operator is used to free the memory taken up by an object.
-
What is the difference between public, protected, and private members of a class?
Private members are accessible only by members and friends of the class. Protected members are accessible by members and friends of the class and by members and friends of derived classes. Public members are accessible by everyone.
-
How do you link a C++ program to C functions?
By using the extern "C" linkage specification around the C function declarations. <P> The candidate should know about mangled function names and type-safe linkages. They should explain how the extern "C" linkage specification statement turns that feature off during compilation so that the linker properly links function calls to C functions.
-
What does extern "C" int func(int *, Foo) accomplish?
It will turn off "name mangling" for func so that one can link to code compiled by a C compiler. </P>
-
Why do C++ compilers need name mangling?
Name mangling is the rule according to which C++ changes function names into function signatures before invoking the linker. Mangled names are used by the linker to differentiate between different functions with the same name. </P>
-
What is function's signature?
function's signature is its name plus the number and types of the parameters it accepts. </P>
-
What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different. <P> The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.
-
What is the difference between function overloading and function overriding?
Overloading is a method that allows defining multiple member functions with the same name but different signatures. The compiler will pick the correct function based on the signature. Overriding is a method that allows the derived class to redefine the behavior of member functions which the derived class inherits from a base class. The signatures of both base class member function and derived class member function are the same; however, the implementation and, therefore, the behavior will differ.
-
Can you overload a function based only on whether a parameter is a value or a reference?
No. Passing by value and by reference looks identical to the caller.
-
Can derived class override some but not all of a set of overloaded virtual member functions inherited from the base class?
Compiler will allow this, but it is a bad practice since overridden member functions will hide all of the inherited overloads from the base class. You should really override all of them.
-
What is the difference between assignment and initialization in C++?
Assignment changes the value of the object that has already been constructed. Initialization constructs a new object and gives it a value at the same time.
-
Name two cases where you MUST use initialization list as opposed to assignment in constructors.
Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them. </P>
-
When are copy constructors called?
Copy constructors are called in three cases: when a function returns an object of that class by value, when the object of that class is passed by value as an argument to a function, and, finally, when you construct an object based on another object of the same class (Circle c1=c2;). </P>
Medior Questions
-
What is the difference between
deleteanddelete[[[ | []]?deletedeletes one object;delete[[[ | []]deletes an array of objects. </P> -
What is the difference between non-virtual and virtual functions?
The behavior of a non-virtual function is known at compile time while the behavior of a virtual function is not known until the run time.
-
What is a pure virtual function?
A pure virtual function is a function declared in a base class that has no definition relative to the base.
-
How do you know that your class needs a virtual destructor?
If your class has at least one virtual function, you should make a destructor for this class virtual. This will allow you to delete a dynamic object through a pointer to a base class object. If the destructor is non-virtual, then the wrong destructor will be invoked during deletion of the dynamic object.
-
What is an abstract base class?
A class that has one or more pure virtual functions.
-
What is your reaction to this line of code?
delete this; <P> It's not a good practice. <P> A good programmer will insist that the statement is never to be used if the class is to be used by other programmers and instantiated as static, extern, or automatic objects. That much should be obvious. <P> The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in.
-
What is a default constructor?
A constructor that has no arguments or one where all the arguments have default argument values. <P> The candicate should know that if you don't code a default constructor, the compiler provides one if there are no other constructors. If you are going to instantiate an array of objects of the class, the class must have a default constructor.
-
Why do you have to provide your own copy constructor and assignment operator for classes with dynamically allocated memory?
If you don't, the compiler will supply and execute the default constructor and the assignment operator, but they will not do the job correctly. The default assignment operator does memberwise assignment and the default copy constructor does memberwise copy. In both cases you will only assign and manipulate pointers to dynamic memory, which will lead to memory leaks and other abnormalities. You should write your own assignment operator and copy constructor, which would copy the pointer to memory so that each object has its own copy. </P>
-
Explain the ISA and HASA class relationships. How would you implement each in a class design?
A specialized class "is a" specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an Employee "has a" Salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.
-
What is the difference between a shallow copy and a deep copy?
A shallow copy simply creates a new object and inserts in it references to the members of the original object. A deep copy constructs a new object and then creates in it copies of each of the members of the original object.
-
What is the difference between
MyClass p;andMyClass p();?MyClass p;creates an instance of classMyClassby calling a constructor forMyClass.MyClass p();declares function p which takes no parameters and returns an object of classMyClassby value. -
What issue do auto_ptr objects address?
If you use auto_ptr objects you would not have to be concerned with heap objects not being deleted even if the exception is thrown. </P>
-
What functions does C++ silently write and call?
Constructors, destructors, copy constructors, assignment operators, and address-of operators. </P>
-
Does the compiler guarantee that initializers will be executed in the same order as they appear on the initialization list?
No. C++ guarantees that base class subobjects and member objects will be destroyed in the opposite order from which they were constructed. This means that initializers are executed in the order, which supports the above-mentioned guarantee. </P>
Senior Questions
-
Who is Brad Cox?
He authored Object-oriented Programming, An Evolutionary Approach, a book that is generally credited with launching today's industry-wide enthusiasm for object technology. </P>
-
Who is Grady Booch?
Grady Booch has been an object- based/oriented advocate for some time. His latest notations are often referred to as simply the "Booch" method or notation. </P>
-
How are prefix and postfix versions of operator++() differentiated?
The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter. </P>
-
Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered. </P>
-
Is there any problem with the following:<P>
char *a = NULL;
char& p = *a;?The result is undefined. You should never do this. A reference must always refer to some object. </P>
Advanced Questions
-
What is a mutable member?
One that can be modified by the class even when the object of the class, or the member function doing the modification, is const.
-
Why were the templates introduced?
Many data structures and algorithms can be defined independently of the type of data they work with. You can increase the amount of shared code by separating data-dependent portions from data-independent portions, and templates were introduced to help you do that.
-
What is the difference between
static_cast<RWTime>(*this) += 5;andstatic_cast<RWTime&>(*this) += 5;?If you cast
*thisto be anRWTimeobject, the copy constructor forRWTimewill be called and the new object will be the target of the assignment,*thiswill remain unchanged. Hardly what you want. The second instance actually incrementsthisby 5.
Other Resources
- General Programming Interview Questions
- C++ FAQ LITE — Frequently Asked Questions
- Guru of the Week
- C++ interview questions
- C/C++ Interview Questions
- Gimpel C++ Bug List - A good training ground for understanding C++ better.
