C++ syntax, semantics and concepts questions

  1. What is an object in C++?

An object is a package that contains related data and instructions. The data relates to what the object represents, while the instructions define how this object relates to other objects and itself.

  1. What is a message?

A message is a signal from one object to another requesting that a computation take place. It is roughly equivalent to a function call in other languages.

  1. What is a class?

A class defines the characteristics of a certain type of object. It defines what its members will remember, the messages to which they will respond, and what form the response will take.

  1. What is an instance?

An individual object that is a member of some class.

  1. What is a super-class?

Given a class, a super-class is the basis of the class under consideration. The given class is defined as a subset (in some respects) of the super-class. Objects of the given class potentially posses all the characteristics belonging to objects of the super-class.

  1. What is inheritance?

Inheritance is property such that a parent (or super) class passes the characteristics of itself to children (or sub) classes that are derived from it. The sub-class has the option of modifying these characteristics in order to make a different but fundamentally related class from the super-class.

  1. To what does message protocol refer?

An object's message protocol is the exact form of the set of messages to which the object can respond.

  1. What is polymorphism?

Polymorphism refers to the ability of an object to respond in a logically identical fashion to messages of the same protocol, containing differing types of objects. Consider 1 + 5 and 1 + 5.1. In the former, the message "+ 5" is sent to an object of class integer (1). In the later, the message "+ 5.1" is sent to the same integer object. The form of the message (its protocol) is identical in both cases. What differs is the type of object on the right-hand side of these messages. The former is an integer object (5) while the later is a floating point object (5.1). The receiver (1) appears (to other objects) to respond in the same way to both messages. Internally, however, it knows that it must treat the two types of objects differently in order to obtain the same overall response.

  1. What are instance variables?

These represent an object's private memory. They are defined in an object's class.

  1. What are class variables?

These represent a class's memory which it shares with each of its instances.

  1. What is a method?

A method is a class's procedural response to a given message protocol. It is like the definition of a procedure in other languages.

  1. In C++ what is a constructor? A destructor?

A constructors and destructors are methods defined in a class that are invoked automatically when an object is created or destroyed. They are used to initialize a newly allocated object and to cleanup behind an object about to be removed.

  1. Compare and contrast C and C++.

Comparison: C++ is an extension to the C language. When C++ is used as a procedural language, there are only minor syntactical differences between them.

Contrast: When used as a procedural language, C++ is a better C because:

    1. It vigorously enforces data typing conventions.
    2. It allows variables to be defined where they are used.
    3. It allows the definition of real (semantically significant) constants.
    4. It allows for automatic pointer dereferencing.
    5. It supports call-by-reference in addition to call-by-value in functions.
    6. It supports tentative variable declarations (when the type and location of a variable cannot be known before hand.

As an object oriented language, C++ introduces much of the OOP paradigm while allowing a mixture of OOP and procedural styles.

  1. What is operator overloading?

It is the process of, and ability to redefine the way an object responds to a C++ operator symbol. This would be done in the object's class definition.

  1. What is cin and cout?

They are objects corresponding to a program's default input and output files.

  1. Contrast procedural and object oriented programming.

The procedural paradigm performs computation through a step-by-step manipulation of data items. Solving problems this way is akin to writing a recipe. ie: All the ingredients (data items) are defined. Next a series of enumerated steps (statements) are defined to transform the raw ingredients into a finished meal.

The object oriented model, in contrast, combines related data and procedural information into a single package called an object. Objects are meant to represent logically separate entities (like real world objects). Objects are grouped together (and defined by) classes. (This is analogous to user defined data types in procedural languages.) Classes may pass-on their "makeup" to classes derived from them. In this way, Objects that are of a similar yet different nature need not be defined from scratch. Computation occurs though the intercommunication of objects. Programming this way is like writing a play. First the characters are defined with their attributes and personalities. Next the dialog is written so that the personalities interact. The sum total constitutes a drama.

  1. How do you link a C++ program to C functions?

By using the extern "C" linkage specification around the C function declarations.

You should know about mangled function names and type-safe linkages. Then you 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. Another acceptable answer is "I don't know. We never had to do that." Merely describing what a linker does would indicate to me that you do not understand the issue that underlies the question.

  1. Explain the scope resolution operator.

The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope.

The answer can get complicated. It should start with "colon-colon," however. (Some readers had not heard the term, "scope resolution operator," but they knew what :: means. You should know the formal names of such things so that you can understand all communication about them.) If you claim to be well into the design or use of classes that employ inheritance, you tend to address overriding virtual function overrides to explicitly call a function higher in the hierarchy. That's good knowledge to demonstrate, but address your comments specifically to global scope resolution. Describe C++'s ability to override the particular C behavior where identifiers in the global scope are always hidden by similar identifiers in a local scope.

  1. What are the differences between a C++ struct and C++ class?

The default member and base class access specifiers are different.

This is one of the commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++ struct is just like a C struct, while a C++ class has inheritance, access specifiers, member functions, overloaded operators, and so on. Some of them have even written books about C++. Actually, 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. Getting this question wrong does not necessarily disqualify you because you will be in plenty of good company. Getting it right is a definite plus.

  1. How many ways are there to initialize an int with a constant?

Two.

There are two formats for initializers in C++ as shown in Example 1. Example 1(a) uses the traditional C notation, while Example 1(b) uses constructor notation. Many programmers do not know about the notation in Example 1(b), although they should certainly know about the first one. Many old-timer C programmers who made the switch to C++ never use the second idiom, although some wise heads of C++ profess to prefer it.

A reader wrote to tell me of two other ways, as shown in Examples 2(a) and 2(b), which made me think that maybe the answer could be extended even further to include the initialization of an int function parameter with a constant argument from the caller.

  1. How does throwing and catching exceptions differ from using setjmp and longjmp?

The throw operation calls the destructors for automatic objects instantiated since entry to the try block.

Exceptions are in the mainstream of C++ now, so most programmers, if they are familiar with setjmp and longjmp, should know the difference. Both idioms return a program from the nested depths of multiple function calls to a defined position higher in the program. The program stack is "unwound" so that the state of the program with respect to function calls and pushed arguments is restored as if the calls had not been made. C++ exception handling adds to that behavior the orderly calls to the destructors of automatic objects that were instantiated as the program proceeded from within the try block toward where the throw expression is evaluated.

It's okay to discuss the notational differences between the two idioms. Explain the syntax of try blocks, catch exception handlers, and throw expressions. Then specifically address what happens in a throw that does not happen in a longjmp. Your answer should reflect an understanding of the behavior described in the answer just given.

One valid reason for not knowing about exception handling is that your experience is exclusively with older C++ compilers that do not implement exception handling. I would prefer that you have at least heard of exception handling, though.

It is not unusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp. Those constructs are not particularly intuitive. A C programmer who has written recursive descent parsing algorithms will certainly be familiar with setjmp/ longjmp. Others might not, and that's acceptable. In that case, you won't be able to discuss how setjmp/longjmp differs from C++ exception handling, but let the interview turn into a discussion of C++ exception handling in general. That conversation will reveal to the interviewer a lot about your overall understanding of C++.

  1. What is your reaction to this line of code?
delete this;

It's not a good practice.

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.

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. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. 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. Subsequent dereferencing of the pointer can and usually does lead to disaster.

A reader pointed out that a class can ensure that its objects are instantiated on the heap by making its destructor private. This idiom necessitates a kludgy DeleteMe kind of function because the instantiator cannot call the delete operator for objects of the class. The DeleteMe function would then use "delete this."

I got a lot of mail about this issue. Many programmers believe that delete this is a valid construct. In my experience, classes that use delete this when objects are instantiated by users usually spawn bugs related to the idiom, most often when a program dereferences a pointer to an object that has already deleted itself.

  1. What is a default constructor?

A constructor that has no arguments or one where all the arguments have default argument values.

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.

  1. What is a conversion constructor?

A constructor that accepts one argument of a different type.

The compiler uses this idiom as one way to infer conversion rules for a class. A constructor with more than one argument and with default argument values can be interpreted by the compiler as a conversion constructor when the compiler is looking for an object of the type and sees an object of the type of the constructor's first argument.

  1. What is the difference between a copy constructor and an overloaded assignment operator?

A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

First, you must know that a copy constructor is one that has only one argument, which is a reference to the same type as the constructor. The compiler invokes a copy constructor wherever it needs to make a copy of the object, for example to pass an argument by value. If you do not provide a copy constructor, the compiler creates a member-by-member copy constructor for you.

You can write overloaded assignment operators that take arguments of other classes, but that behavior is usually implemented with implicit conversion constructors. If you do not provide an overloaded assignment operator for the class, the compiler creates a default member-by-member assignment operator.

This discussion is a good place to get into why classes need copy constructors and overloaded assignment operators. By discussing the requirements with respect to data member pointers that point to dynamically allocated resources, you demonstrate a good grasp of the problem.

  1. When should you use multiple inheritance?

There are three acceptable answers: "Never," "Rarely," and "When the problem domain cannot be accurately modeled any other way."

There are some famous C++ pundits and luminaries who disagree with that third answer, so be careful.

Let's digress to consider this issue lest your interview turn into a religious debate. Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All company cars are vehicles. Some company cars are assets because the organizations own them. Others might be leased. Not all assets are vehicles. Money accounts are assets. Real-estate holdings are assets. Some real-estate holdings are buildings. Not all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes apparent that multiple inheritance is an intuitive way to model this common problem domain. You should understand, however, that multiple inheritance, like a chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except when nothing else will do. Stress this understanding because your interviewer might share the common bias against multiple inheritance that many object-oriented designers hold.

  1. What is a virtual destructor?

The simple answer is that a virtual destructor is one that is declared with the virtual attribute.

The behavior of a virtual destructor is what is important. If you destroy an object through a pointer or reference to a base class, and the base-class destructor is not virtual, the derived-class destructors are not executed, and the destruction might not be complete.

  1. 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.

The answer to this question reveals whether you have an understanding of the fundamentals of object-oriented design, which is important to reliable class design.

There are other relationships. The USESA relationship is when one class uses the services of another. The Employee class uses an object (cout) of the ostream class to display the employee's name onscreen, for example. But if you get ISA and HASA right, you usually don't need to go any further.

  1. When is a template a better solution than a base class?

When you are designing a generic class to contain or otherwise manage objects of other types, when the format and behavior of those other types are unimportant to their containment or management, and particularly when those other types are unknown (thus the genericity) to the designer of the container or manager class.

Prior to templates, you had to use inheritance; your design might include a generic List container class and an application-specific Employee class. To put employees in a list, a ListedEmployee class is multiply derived (contrived) from the Employee and List classes. These solutions were unwieldy and error-prone. Templates solved that problem.

  1. What is the result of compiling this program in a C compiler? in a C++ compiler?
18.       int __ = 0;
19.       main() {
20.       int ___ = 2;
21.       printf("%d\n", ___ + __);
22.       }

On GNU compiler both C and C++ give output as 2. I believe other C++ compiler will complain "syntax error", whereas C compiler will give 2.

  1. 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.

  1. 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.

  1. 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.

  1. What is inheritance ?

Inheritance is the process of deriving classes from other classes. In such a case, the sub-class has an 'is-a' relationship with the super class. For e.g. vehicle can be a super-class and car can be a sub-class derived from vehicle. In this case a car is a vehicle. The super class 'is not a' sub-class as the sub- class is more specialized and may contain additional members as compared to the super class. The greatest advantage of inheritance is that it promotes generic design and code reuse.

  1. What is multiple inheritance ? What are it's 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.

  1. 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.

  1. 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.

  1. 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.

  1. What is UML ?

UML refers to Unified Modeling Language. It is a language used to model OO problem spaces and solutions.

  1. 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.

  1. What are the differences between new and malloc?

Use new in C++ and malloc in C. Correspondingly so, use delete in C++ and free in C. The subject of an installed new handler is fairly deep. In a hyper-abbreviated nutshell, new will invoke a class' constructor. Malloc won't do jack but come back with a heap pointer of some specified size. Malloc requires the type casting during declaration , where as new doesn't need the type casting during declaration.  Bottom line: Never use malloc in C++...and, unless you implement your own, there is no "new" in C.

  1. What is the difference between delete and delete[]?

Whenever you allocate memory with 'new[]', you have to free the memory using 'delete[]'. When you allocate memory with 'new', then use 'delete' without the brackets. You use ‘new []' to allocate an array of values (always starting at the index 0).

  1. What are the differences between a struct in C and in C++?

C structs contain only primitive data types as members, all of which are visible to anything that can access the struct definition, they have no methods and no constructors or destructors, and there's no such thing as inheritance. In C++, a struct is identical to a class except that the members of a struct have public visibility by default, but the members of a class have private visibility by default.


  1. What are the advantages/disadvantages of using #define?

Advantages

1.You can define generic operations (macro are not type-checked), as in

#define next2(ptr) ptr->next->next

which will work on any pointer that points to a struct containing a

next field of the same pointer-type.

 

2. Generally leads to faster code due to the lack of function-call overhead.

 

3. You can pass things other than expression-values to macro, including

types, labels, other macros, statements, and return such things as

a macro's "value." For example, you can define a macro to 'malloc' a block

of memory, including doing the proper type-casting with something like

#define tmalloc(typeName) ((typeName *)malloc(sizeof(typeName)))

 

4. You can define a macro that side-effects a variable without having to

use the '&' operator, as in #define nextPtr(ptr) (ptr = ptr->next)

A function to do the same operation would have to be invoked as

nextPtr(&myPtr) and would not be generic. (On the other hand, things that look like

functions, but perform non-apparent side-effects can also be confusing.)

 

5. A macro that contains errors (e.g. syntax) need not be commented out as

long as it is unused.

 

6. Macros in some contexts where functions cannot, as in:

switch (abs){

case foo(2, 6): /* foo must be a macro here */

...}

Disadvantages

1. No checking (e.g. syntax, type-checking) is done at the macro definition,

but only at its invocation. This can lead to some pretty non-intuitive

error-messages by the time the compiler figures out what's going on.

Additionally, arguments promotions are not done for macros.

 

2. Code is often bulkier because it is expanded in-line.

 

3. You cannot pass a pointer to a macro like you can to a function.

 

4. In many debuggers, you cannot invoke a macro. If you have defined a

function to print out a data object in some readable way, you can

generally invoke it during debugging; had a macro been used to print

the data object instead, you may be out of luck.

 

5. If you change a function definition, you generally only have to recompile

the file where the function is defined (unless the function's interface

changes). If you change a macro definition, you generally have to

recompile all the files that use the macro.

 

  1. What are the advantages/disadvantages of using inline and const?

The advantages of using inline functions are:

    1. Type safety. Inline functions are subject to the same type checking as normal functions. Macros are not type safe.
    2. Correct handling of arguments that have side effects. Inline functions evaluate the expressions supplied as arguments prior to entering the function body. Therefore, there is no chance that an expression with side effects will be unsafe.
    3. Faster than a normal function

The disadvantages of using inline functions are

   An inline function gets compiled as many times as you call it and it also effects filesize.

 


  1. What is the difference between a pointer and a reference?

A pointer can point to many different objects during its life time, a reference can refer to only one object during its lifetime. The reference is simpler and easier to use. References cannot be used for array notation. when using pointers, the address must be dereferenced using the *, whereas,when using references, the address is dereferenced without using any operators at all! References are the preferred way of indirectly accessing a variable. They are also a little

safer than pointers.

 

The difference is that a pointer need not have a valid value, and a reference must always refer to an object (i.e. a reference must be initialized, a pointer need not be).

 

Performance (and underlying implementation) is typically the same, although an optimizing compiler might in some cases generate faster code for the reference parameter, because it knows the address is not NULL.


  1. When would you use a pointer? A reference?

So when should either option be used for passing parameters? Unless it is desirable to be able to provide NULL as a parameter, references ought to be preferred in C++ programs.


  1. What does it mean to take the address of a reference?

A reference is an alias or an alternative name for an object. All operations applied to a reference act on the object to which the reference refers. The address of a reference is the address of the aliased object. Passing an object by reference enables the function to change the object being referred to without creating a copy of the object within the scope of the function. Only the address of the actual original object is put on the stack, not the entire object.


  1. What does it mean to declare a function or variable as static?

The use of static inside a function is the simplest. It simply means that once the variable has been initialized, it remains in memory until the end of the program; the variable sticks around, maintaining its value, until the program completely ends.

The second use of static is inside a class definition. While most variables declared inside a class occur on an instance-by-instance basis. a static member variable has the same value in any instance of the class and doesn't even require an instance of the class to exist. To access the static member, you use the scope operator, ::, when you refer to it through the name of the class.

static member functions of a class are functions that do not require an instance of the class, and are called the same way you access static member variables -- with the class name rather than a variable name. Static member functions can only operate on static members, as they do not belong to specific instances of a class. Static member functions can be used to modify static member variables to keep track of their values

  1. What is the order of initalization for data?


  1. What is name mangling/name decoration?

Name mangling, (the more politically correct term is name-decoration, although it is rarely used) is a method used by a C++ compiler to generate unique names for identifiers in a program.


  1. What kind of problems does name mangling cause?

One of the problems with name mangling is that the C++ standard (currently [ISO14882]) does not define how names have to be mangled; thus every compiler mangles names in its own way. Some compilers even change their name mangling algorithm between different versions (notably g++ 2.x and 3.x). Even if you worked out how your particular compiler mangles names (and would thus be able to load functions via dlsym), this would most probably work with your compiler only, and might already be broken with the next version.

  1. How do you work around them?


  1. What is a class?

A class in C++ is an encapsulation of data members and functions that manipulate the data. The class can also have some other important members which are architecturally important. 

  1. What are the differences between a struct and a class in C++?

The only difference between structs and classes in C++ is that the members of a struct have public visibility by default, and the members of a class have private visibility by default.

  1. What is the difference between public, private, and protected access?

         Public variables, are variables that are visible to all classes.

Private variables, are variables that are visible only to the class to which they belong and friend classes

Protected variables, are variables that are visible only to the class to which they belong, and any subclasses(derived classes).


  1. For class CFoo { }; what default methods will the compiler generate for you?


  1. How can you force the compiler to not generate them?


  1. What is the purpose of a constructor? Destructor?

The purpose of a constructor is to initialize data members and sometimes to obtain resources such as memory, or a mutex or lock on a shared resource such as a hardware device. The purpose of the destructor is clean up. It is used to free memory and to release any locks or mutexes on system resources.

  1. What is a constructor initializer list?

The constructor initializer list – which, as the name implies, occurs only in the definition of the constructor – is a list of “constructor calls” that occur after the function argument list and a colon, but before the opening brace of the constructor body. This is to remind you that the initialization in the list occurs before any of the main constructor code is executed. This is the place to put all const initializations. The proper form for const inside a class is shown here:

               //: C08:ConstInitialization.cpp
               // Initializing const in classes
               #include <iostream>
               using namespace std;
 
               class Fred {
                 const int size;
               public:
                 Fred(int sz);
                void print();
               };
 
               Fred::Fred(int sz) : size(sz) {}
               void Fred::print() { cout << size << endl; }
               
               int main() {
                Fred a(1), b(2), c(3);
               a.print(), b.print(), c.print();
               } ///:~


  1. When must you use a constructor initializer list?

Suppose you have a class member that is itself a class or struct, and this class only has one constructor that requires an argument.

class CMember {

public:

    CMember(int x) { ... }

};

 

Since CMember has an explicit constructor, the compiler does not generate a default constructor (one with no arguments) and there is no way to create an instance of CMember without an integer.

CMember* pm = new CMember;        // Error!!

CMember* pm = new CMember(2);     // OK

How do you initialize CMember if it's a member of another class? You must use the member initialization list.

class CMyClass {

    CMember m_member;

public:

    CMyClass();

};

// must use initializer list

CMyClass::CMyClass() : m_member(2)

{•••}

There's simply no other way to pass the argument to m_member. The same is true if the member is a const object or reference. According to the rules of C++, const objects and references cannot be assigned; they can only be initialized.

  1. What is a: Constructor? Destructor? Default constructor? Copy constructor? Conversion constructor?

The constructor is a member function of a class. It is invoked every time an object is created. It no explicit constructors are defined, the default constructor, which the compiler provides is used.

The constructor is a member function of a class. It is invoked every time an object is created. It no explicit constructors are defined, the default constructor, which the compiler provides is used.

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

A copy constructor for a class A is a constructor whose first parameter is of type A&, const A&, volatile A&, or const volatile A&. Copy constructors are used to make a copy of one class object from another class object of the same class type

class X {

public:

 

  // default constructor, no arguments

  X();

 

  // constructor

  X(int, int , int = 0);

 

  // copy constructor

  X(const X&);

 

  // error, incorrect argument type

  X(X);

};

 

When a class constructor in C++ has only one parameter and that parameter isn't of the same type as that class, it is assumed to be a conversion constructor for converting the passed type to the type of the class

class HelloWorld{
private:

char * mydatahere;
public:

HelloWorld(int);
}

While the inexperienced programmer may think that the constructor in this function takes an integer variable, infact the compiler expects a function that will convert the integer to a HelloWorld object. Now, if this isn't what you want, you need to use the explicit keyword. This will make sure the compiler treats the constructor as a normal constructor, and not as a conversion constructor. Like so:

class HelloWorld{
private:

char * mydatahere;
public:

explicit HelloWorld(int);
}

  1. What does it mean to declare a... member function as virtual? member function as static? member varible as static? Constructor as static? destructor as static?

To specify that the compiler match a function call with the correct function definition at run time is called dynamic binding. We declare a function with the keyword virtual if we want the compiler to use dynamic binding for that specific function.

A static member function in a class can access only other static members of a class or variables which are not members of its class. It can be invoked even without an object instance, unlike any other member functions. A static member function does not have a this pointer. A static member function cannot be declared with the keywords virtual, const, volatile, or const volatile.

A static member variable has the same value in any instance of the class and doesn't even require an instance of the class to exist. To access the static member, we use the scope operator, ::, when we refer to it through the name of the class.

A static constructor is defined as a function that performs initializations before the main() function gets control. Static constructors are used to initialize static class members with values that cannot be computed at compile time. Dynamic initialization is performed by a static constructor, defined with a special syntax static this().The static in the static constructor declaration is not an attribute, it must appear immediately before the this

class Foo

{

    static int a;                             // default initialized to 0

    static int b = 1;

    static int c = b + a;  // error, not a constant initializer

 

    static this()                             // static constructor

    {

   a = b + 1;                               // a is set to 2

   b = a * 2;                               // b is set to 4

    }

}

A static destructor gets called on program termination, but only if the static constructor completed successfully. Static destructors have empty parameter lists. Static destructors get called in the reverse order that the static constructors were called in. The static in the static denstructor declaration is not an attribute, it must appear immediately before the ~this.

  1. Can you explain the term "resource acqusition is initialization?"

Many programming tasks share a common pattern: First we acquire/initialize a resource, then we perform the necessary processing and finally, we release/return the acquired resource. In C++ it is supported by the notion of a constructors and destructors. We take advantage of this pair to implement the RAII idiom. The constructor will take care of the initialization part, whereas the destructor will do the inverse, thereby freeing the programmer from the burden of these repetitive yet crucial steps.


  1. What is a "pure virtual" member function?

A pure virtual function is merely an interface and can be thought of as a way to enforce policy. A pure virtual function should be used when subclasses implement the same interface completely differently. For example, a persistence interface can have a write operation to store the state of an object. Yet, each class that implements this interface performs individual operations to store its state into a file:

 

               class persistent {

                               public:

                                virtual void Write () = 0;

               };

               class Clock: public persistent {

                               public:

                               void Write() {_} // implement the interface

               };

               class Date: public persistent {

                               public:

                               void Write() {_} // implement the interface

               };

If the definition of a virtual function is replaced by a pure specifier in the declaration of the function, the function is said to be declared pure. A class that has at least one pure virtual function is called an abstract class.

  1. What is the difference between public, private, and protected inheritance?

A member (either data member or member function) declared in a private section of a class can only be accessed by member functions and friends of that class

A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes

A member (either data member or member function) declared in a public section of a class can be accessed by anyone

  1. What is virtual inheritance?

Virtual inheritance in C++ solves some of the problems caused by multiple inheritance by having clarifying disambiguity over which Ancestor Class members to use. It is used when the inheritance is representing restrictions of a set rather than composition of parts. You denote a member as virtual by the virtual keyword.

  1. What is placement new?

Operator new allocates memory from the heap, on which an object is constructed. Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time):

 

               void placement() {

 

                               char *buf  = new char[1000];   //pre-allocated buffer

                               string *p = new (buf) string("hi");  //placement new

                               string *q = new string("hi");  //ordinary heap allocation

                               cout<c_str()<c_str();<< } buf; [] delete q; ...>

  1. What is the difference between operator new and the new operator?

The new operator provides dynamic storage allocation. If you prefix new with the scope resolution operator (::), the global operator new() is used

               #include <new>

               using namespace std;

 

               class X

               {

               public:

                 void* operator new(size_t,int, int){ /* ... */ }

               };

 

               // ...

 

               int main ()

               {

                                X* ptr = new(1,2) X;

               }

  1. What is exception handling?

Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program.

The exception handling mechanism is made up of the following elements:

·         try blocks: a block of code that may throw an exception that you want to handle with special processing

·         catch blocks or handlers: a block of code that is executed when a try block encounters an exception

·         throw expression: indicates when your program encounters an exception

·         exception specifications: specify which exceptions (if any) a function may throw

·         unexpected() function: called when a function throws an exception not specified by an exception specification

·         terminate() function: called for exceptions that are not caught

  1. Explain what happens when an exception is thrown in C++.

It depends on whether or not we have any code that catches the exception.

  1. What happens if an exception is not caught?

An uncaught exception would cause the program to terminate.

  1. What happens if an exception is throws from an object's constructor?

It means that construction has failed, the object never existed, its lifetime never began. Indeed, the only way to report the failure of construction -- that is, the inability to correctly build a functioning object of the given type -- is to throw an exception. A destructor will never be called if the constructor didn't succeed.

  1. What happens if an exception is throws from an object's destructor?

No matter how the destructor terminates, the object does not exist anymore. Thus, in the case of the destructor, we are forced to complete the job no matter what.

  1. What are the costs and benefits of using exceptions?

Exception handling increases the program reliability. Program does not crash as in assert.

1.      you can catch various types of errors (you aren't restricted to a single error class),

2.      different levels of code can catch different exceptions,

3.      you don't have to worry about checking errors unless you want to ignore or handle a particular case,

4.      code is generally more readable (the 'return' value is reclaimed and the need for checking error states is reduced),

5.      exception-safe coding is more maintainable (return-anywhere safe as well) by more people, and

6.      much of the work that may be required in using API functions in an exception-safe manner can be hidden by good programmers in good class wrappers to be used by all.

 

Disadvantages

The disadvantage of exceptions is that you need to enable exception handling in the compiler with the penalty of the overhead in creating bunches of extra stack frames, and all code where exceptions can be thrown must be written in an exception safe manner

  1. When would you choose to return an error code rather than throw an exception?

Applicational logic or flow control.

  1. What is a template?

A template describes a set of related classes or set of related functions in which a list of parameters in the declaration describe how the members of the set vary. The compiler generates new classes or functions when you supply arguments for these parameters; this process is called template instantiation. This class or function definition generated from a template and a set of template parameters is called a specialization.

  1. What is partial specialization or template specialization?

For class templates only, you can define partial specializations that don't have to fix all of the primary (unspecialized) class template's parameters.

Here is an example from 14.5.4 [temp.class.spec]. The first template is the primary class template:

          template<class T1, class T2, int I>

          class A             { };             // #1

We can specialize this for the case when T2 is a T1*:

         template<class T, int I>

         class A<T, T*, I>   { };             // #2

Or for the case when T1 is any pointer:

         template<class T1, class T2, int I>

         class A<T1*, T2, I> { };             // #3

Or for the case when T1 is int and T2 is any pointer and I is 5:

         template<class T>

        class A<int, T*, 5> { };             // #4

   Or for the case when T2 is any pointer:

         template<class T1, class T2, int I>

         class A<T1, T2*, I> { };             // #5

Declarations 2 to 5 declare partial specializations of the primary template. The compiler will then choose the appropriate template. From 14.5.4.1 [temp.class.spec.match]:

        A<int, int, 1>   a1;  // uses #1

         A<int, int*, 1>  a2;  // uses #2, T is int,

                        //          I is 1

         A<int, char*, 5> a3;  // uses #4, T is char

         A<int, char*, 1> a4;  // uses #5, T1 is int,

                        //          T2 is char,

                        //          I is 1

         A<int*, int*, 2> a5;  // ambiguous:

                        // matches #3 and #5

 

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization. A primary template is the template that is being specialized.

Explicit specialization lets you write a specific implementation for a particular combination of template parameters. For example, given the function template:

         template<class T> void sort(Array<T>& v) { /*...*/ };

If we have a faster (or other specialized) way we want to deal specifically with arrays of char*'s, we could explicitly specialize:

        template<> void sort<char*>(Array<char*>&);

The compiler will then choose the most appropriate template:

          Array<int>   ai;

         Array<char*> apc;

 

         sort( ai );       // calls sort<int>

         sort( apc );      // calls specialized sort<char*>


  1. How can you force instantiation of a template?
You can explicitly tell the compiler when it should generate a definition from a template. This is called explicit
 
instantiation. template<class T> class Array { void mf(); };

               template class Array<char>;      // explicit instantiation

               template void Array<int>::mf();  // explicit instantiation

 

               template<class T> void sort(Array<T>& v) { }

               template void sort(Array<char>&); // explicit instantiation

              

   A template declaration must be in scope at the point of instantiation of the template's explicit instantiation. An explicit instantiation of a template specialization is in the same namespace where you defined the template

 

       

  1. What is an iterator?

Iterators are used to access members of the container classes, and can be used in a similar manner to pointers. For example, one might use an iterator to step through the elements of a vector. There are several different types of iterators:

  1. What is an algorithm (in terms of the STL/C++ standard library)?

The algorithms of STL can be divided into two groups by their memory access pattern: scanning algorithms and random access algorithms. Scanning algorithms work with Input, Output, Forward, and Bidirectional iterators only. Since random access operations are not allowed with these kinds of iterators, the algorithms inherently exhibit strong spatial locality of reference. Random access algorithms require RandomAccess iterators, hence may perform many random I/Os 4. For such algorithms, STXXL provides specialized I/O-efficient implementations that work with STL-user layer external memory containers

  1. What is std::auto_ptr?

auto_ptr owns a dynamically allocated object and performs automatic cleanup when the object is no longer needed. Here's a simple example of code that's unsafe without auto_ptr:

               // Example 1(a): Original code
                 //
                 void f()
                 {
                   T* pt( new T );

                  /*...more code...*/

                  delete pt;
                }

Most of us write code like this every day. If f() is a three-line function that doesn't do anything exceptional, this may be fine. But if f() never executes the delete statement, either because of an early return or because of an exception thrown during execution of the function body, then the allocated object is not deleted and we have a classic memory leak.

A simple way to make Example 1(a) safe is to wrap the pointer in a "smarter" pointer-like object that owns the pointer and that, when destroyed, deletes the pointed-at object automatically. Because this smart pointer is simply used as an automatic object (that is, one that's destroyed automatically when it goes out of scope), it's reasonably called an "auto" pointer:

                // Example 1(b): Safe code, with auto_ptr
                //
                void f()
                {
                 auto_ptr<T> pt( new T );

                /*...more code...*/

                } // cool: pt's destructor is called as it goes out
                // of scope, and the object is deleted automatically


  1. What is wrong with this statement? std::auto_ptr ptr(new char[10]);

Whenever we are using new [], we need a matching delete[] to properly destroy the array. However, auto_ptr's destructor uses only scalar delete. The result of binding an array to an auto_ptr is therefore undefined, because the array isn't deleted properly.

  1. It is possible to build a C++ compiler on top of a C compiler. How would you do this?

Note: I've only asked this question once; and yes, he understood that I was asking him how cfront was put together.

You must use your C++ compiler when compiling main() (e.g., for static initialization)

Your C++ compiler should direct the linking process (e.g., so it can get its special libraries)

Your C and C++ compilers probably need to come from same vendor and have compatible versions (e.g., so they have the same calling conventions)

  1. What output does the following code generate? Why? What output does it generate if you make A::Foo() a pure virtual function?
78.       #include 
79.       class A {
80.       public:
81.       A() {
82.       this->Foo();
83.       }
84.       virtual void Foo() {
85.       cout << "A::Foo()" << endl;
86.       }
87.       };
88.       class B : public A {
89.       public:
90.       B() {
91.       this->Foo();
92.       }
93.       virtual void Foo() {
94.       cout << "A::Foo()" << endl;
95.       }
96.       };
97.       int main(int, char**)
98.       {
99.       B       objectB;
100.   }
101.    
102.   p {return 0;
103.   }


  1. What output does this program generate as shown? Why?
105.   #include 
106.   class A {
107.   public:
108.   A() {
109.   cout << "A::A()" << endl;
110.   }
111.   ~A() {
112.   cout << "A::~A()" << endl; throw "A::exception";
113.   }
114.   };
115.   class B {
116.   public:
117.   B() {
118.   cout << "B::B()" << endl; throw "B::exception";
119.   }
120.   ~B() {
121.   cout << "B::~B()";
122.   }
123.   };
124.   int main(int, char**) {
125.   try {
126.   cout << "Entering try...catch block" << endl;
127.   }
128.    
129.   p {A    objectA;
130.   B       objectB;
131.   }
132.    
133.   p {cout << "Exiting try...catch block" << endl;
134.   } catch (char* ex) {
135.   cout << ex << endl;
136.   }
137.   }
138.    
139.   p {return 0;
140.   }


  1. C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).


  1. I was given a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.