C++ Pro Flashcards

1
Q

Q: Give the type for a function pointer to a member function of Foo that returns int and takes a char and float parameters.

A

A: int (Foo::*)(char,float)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q: What are some ways try / catch / throw can improve software quality?

A

A: By eliminating one of the reasons for if statements. The commonly used alternative to try / catch / throw is to return a return code (sometimes called an error code) that the caller explicitly tests via some conditional statement such as if. For example, printf(), scanf() and malloc() work this way: the caller is supposed to test the return value to see if the function succeeded. Although the return code technique is sometimes the most appropriate error handling technique, if statements can be the source of many bugs.

throw also forces a run-time check, if only trivially, because an uncaught exception will generate a message to a user, hopefully containing information about the type of fault. A return code, on the other hand, can be ignored causing a crash with no useful message. The source of the fault must then be traced backwards from the crash point, which can be far away in the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Q: What is the assignment operator?

A

A: The default assignment operator handles assigning one object to another of the same class. Member to member copy is done via shallow copy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?

A

A: No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Q: What is a class?

A

A: A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q: How do you handle a constructor that fails?

A

A: throw an exception. Constructors don’t have a return type, so it’s not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: How can I provide input for my class Fred?

A

A: Use operator overloading to provide a friend right-shift operator, operator>>. This is similar to the output operator, except the parameter doesn’t have a const: “Fred&” rather than “const Fred&”.

class Fred
{
public:
friend std::istream& operator>> (std::istream& i, Fred& fred);
private:
int i_; // Just for illustration
};

std::istream& operator>> (std::istream& i, Fred& fred)
{
return i >> fred.i_;
}

int main(){
Fred f;
std::cout << “Enter a Fred object: “;
std::cin >> f;
}

Note that operator>> returns the stream. This is so the input operations can be cascaded and/or used in a while loop or if statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Q: What are some advantages/disadvantages of using friend functions?

A

A: They provide a degree of freedom in the interface design options. Member functions and friend functions are equally privileged (100% vested). The major difference is that a friend function is called like f(x), while a member function is called like x.f(). Thus the ability to choose between member functions (x.f()) and friend functions (f(x)) allows a designer to select the syntax that is deemed most readable, which lowers maintenance costs.

The major disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend, the friend function should call a hidden (usually protected) virtual member function. This is called the Virtual Friend Function Idiom.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: Should constructors use “initialization lists” or “assignment”?

A

A: Initialization lists. In fact, as a rule constructors should initialize all member objects in the initialization list. Every rule has exceptions. This might happen when your class has two constructors that need to initialize this object’s data members in different orders. Or it might happen when two data members are self-referential. Or when a data- member needs a reference to this object, and you want to avoid a compiler warning about using the this keyword prior to the open curly brace of the constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: What is the down side with runtime type identification (RTTI)?

A

A: The run time type identification comes with a performance penalty. Both dynamic_cast and typeid require RTTI to be maintained by the run time environment. Compiler support for RTTI may be optional.

int main () {
   int \* a,b;
   a=0; b=0;
   if (typeid(a) != typeid(b))
   {
     cout \<\< "a and b are of different types:\n";
     cout \<\< "a is: " \<\< typeid(a).name() \<\< '\n';
     cout \<\< "b is: " \<\< typeid(b).name() \<\< '\n';
   }
   return 0;
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Q: When you write a derived class’s destructor, do you need to explicitly call the destructor for my base class?

A

A: No. You never need to explicitly call a destructor (except with placement new).

A derived class’s destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

In the event of multiple inheritance, direct base classes are destructed in the reverse order of their appearance in the inheritance list.

Order dependencies with virtual inheritance are trickier. If you are relying on order dependencies in a virtual inheritance hierarchy, you’ll need a lot more information than we have here.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: What is copy constructor?

A

A: Constructor that initializes its object member variables ( byshallow copying) with another object of the same class. If you don’t implement one in your class then thecompiler implements one for you. Dor example:

(a) Boo Obj1(10); // calling Boo constructor
(b) Boo Obj2(Obj1); // calling boo copy constructor
(c) Boo Obj2 = Obj1;// calling boo copy constructor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Q: What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?

A

A: Multiple Inheritance is the process whereby a child can be derived from more than one parent 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(ambiguity) when two base classes implement a method with the same name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q: Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?

A

A: 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Q: How do I convert a number to a string?

A

A: The simplest way is to use a stringstream:

inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion(“stringify(double)”);
return o.str();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q: Should a class declare a member function or a friend function?

A

A: Use a member when you can, and a friend when you have to. Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don’t allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation). In other cases, choose a member function over a friend function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Q: What are the differences between a C++ struct and C++ class?

A

A: 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 specifes, member functions, overloaded operators, and so on. 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 specified and private base-class inheritance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Q: How do you wrap a new Foo() in a smart pointer?

A

A:

std::auto_ptr z (new Foo());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Q: What is a const_cast?

A

A: It changes the constness of any pointer or reference, so converts from const to not-const, or from not-const to const.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Q: How many ways are there to initialize an int with a constant?

A

A: Two that I know of:

(a) int foo = 123;
(b) int bar(123);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q: Do I need to check for NULL before delete p?

A

A: No. The C++ language guarantees that delete p will do nothing if p is equal to NULL. Since you might get the test backwards, and since most testing methodologies force you to explicitly test every branch point, you should not put in the redundant if test.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Q: How do I allocate / unallocate an array of things?

A

A: Use p = new T[n] and delete[] p:

Any time you allocate an array of objects via new (usually with the [n] in the new expression), you must use [] in the delete statement. This syntax is necessary because there is no syntactic difference between a pointer to a thing and a pointer to an array of things (something we inherited from C).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q: What are storage qualifiers in C++ ?

A

A: They are:

const: Indicates that memory once initialized, should not be altered by a program.
volatile: Indicates that the value in the memory location can be altered even though nothing in the program code modifies the contents. Forces compiler to generate code to read that storage every time it is used, even if no code has written to the location.
mutable: Indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q: What are the benefits of operator overloading?

A

A: By overloading standard operators on a class, you can exploit the intuition of the users of that class. This lets users program in the language of the problem domain rather than in the language of the machine.The ultimate goal is to reduce both the learning curve and the defect rate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Q: What is an inline function?

A

A: The inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler’s discretion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Q: After p = new Fred[n], how does the compiler know there are n objects to be destructed during delete[] p?

A

A: Short answer: Magic. Long answer: The run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the pointer, p. There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:Over-allocate the array and put n just to the left of the first Fred object. Use an associative array with p as the key and n as the value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q: What are C++ storage classes?

A

A:

auto: The default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block.
register: a type of auto variable. A suggestion to the compiler to use a CPU register for performance.
static: A variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution.
extern: A static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q: What is stack unwinding?

A

A: It is a process during exception handling when the destructor is called for all local objects in the stack between the place where the exception was thrown and where it is caught.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Q: What operators can/cannot be overloaded?

A

A: Most can be overloaded. The only C operators that can’t be are . and ?: (and sizeof, which is technically an operator).

C++ adds a few of its own operators, most of which can be overloaded except :: and .*.

Here’s an example of the subscript operator (it returns a reference).

class Array {
public:
int& operator[] (unsigned i) { if (i > 99) error(); return data[i]; }
private:
int data[100];
};

int main()
{
Array a;
a[10] = 42;
a[12] += a[13];

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Q: What is a Pure Virtual Function?

A

A: virtual foo() = 0;It is an error to define a pure virtual function in the class where it was declared or to instantiate the abstract class. Subclasses may define the function, otherwise it remains a pure virtual function in the subclass as well.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Q: How does free know the size of memory to be deleted.?int *i = (int *)malloc(12); followed by free(i); how did free function call know how much of memory to delete?

A

A: It depends on the implementation, but there is usually a malloc header added to all the memory allocated through malloc. On Linux it’s 4 bytes of memory preceding the memory returned to you, which contains the number of bytes allocated + 4(itself). So when you say,int *i = (int *)malloc(12); it allocates 16 bytes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Q: Can you drop the [] when deleteing array of some built-in type (char, int, etc)?

A

A: No! Sometimes programmers think that the [] in the delete[] p only exists so the compiler will call the appropriate destructors for all elements in the array. Because of this reasoning, they assume that an array of some built-in type such as char or int can be deleted without the []. But this is wrong, and it can cause a disaster at runtime. In particular, the code that’s called for delete p is operator delete(void*), but the code that’s called for delete[] p is operator delete. The default behavior for the latter is to call the former, but users are allowed to replace the latter with a different behavior (in which case they would normally also replace the corresponding new code in operator new). If they replaced the delete[] code so it wasn’t compatible with the delete code, and you called the wrong one (i.e., if you said delete p rather than delete[] p), you could end up with a disaster at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Q: What are the access privileges in C++? What is the default access level?

A

A: 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 its sub-classes. Public members of a class can be accessed by anyone.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Q: When should you use references, and when should you use pointers?

A

A: Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don’t need “reseating”. This usually means that references are most useful in a class’s public interface. References typically appear on the skin of an object, and pointers on the inside.

The exception to the above is where a function’s parameter or return value needs a “sentinel” reference, a special reference value that does not refer to an object.

Additionally, pointers are useful when you need one variable to indicate varying objects over its lifetime. Permanent relationships could be modeled with a reference, but a more dynamic relationship can use a pointer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Q: What are some examples of operator overloading?

A

A: Here are a few of the many examples of operator overloading:

myString + yourString might concatenate two std::string objects

myDate++ might increment a Date object

a * b might multiply two Number objects

a[i] might access an element of an Array

objectx = *p might dereference a “smart pointer” that “points” to a disk record

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Q: Do I need to check for NULL after p = new Fred()?

A

A: No. It turns out to be a real pain to always write explicit NULL tests after every new allocation. Code like the following is very tedious:

Fred\* p = new Fred();
 if (p == NULL) throw std::bad\_alloc();

Take heart. In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never returns NULL!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Q: Why can’t you open a file in a different directory such as “..\test.dat”?

A

A: Because “\t” is a tab character.You should use forward slashes in your filenames, even on operating systems that use backslashes (DOS, Windows, OS/2, etc.).

Remember, the backslash (“") is used in string literals to create special characters: “\n” is a newline, “\b” is a backspace, and “ “ is a tab, “\a” is an “alert”, “\v” is a vertical-tab, etc.

Use “/”, even on systems that use a “" as the directory separator. This works because the library routines on these operating systems handle “/” and “" interchangeably.

Of course you could use “\” instead, but it is hard to read and easy to miss one “".

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Q: Is the default constructor for Fred always Fred::Fred()?

A

A: No. A “default constructor” is a constructor that can be called with no arguments.

One example of this is a constructor that takes no parameters. Another example of a “default constructor” is one that can take arguments, provided they are given default values:

class Fred {
 public:Fred(int i=3, int j=5);
 // Default constructor: can be called with no args
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Q: Is there any difference between List x; and List x();?

A

A: A big difference! Suppose that List is the name of some class. Then function f() declares a local List object called x:

void f() {
 List x; // Local object named x (of class List)
 ...}

But function g() declares a function called x() that returns a List:

void g() {
 List x(); // Function named x (that returns a List)
 ...}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Q: In the following block, what gets cleaned up at the end of scope?

{

Thing* t = new Thing;

}

A

A: t gets deleted (just the pointer), but the instance of Thing does not. This may be a memory leak.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Q: Can you overload operator== so it lets you compare two char[] using a string comparison?

A

A: No: at least one operand of any overloaded operator must be of some user-defined type (most of the time that means a class).But even if C++ allowed you to do this, which it doesn’t, you wouldn’t want to do it anyway since you really should be using a std::string-like class rather than an array of char in the first place since arrays are evil.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Q: What is Memory alignment?

A

A: The term alignment primarily means the tendency of an address pointer value to be a multiple of some power of two. So a pointer with two byte alignment has a zero in the least significant bit. And a pointer with four byte alignment has a zero in both the two least significant bits. And so on. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Q: What are some guidelines / “rules of thumb” for overloading operators?

A

A: Here are a few guidelines / rules of thumb:

If you define arithmetic operators, maintain the usual arithmetic identities. For example, if your class defines x + y and x - y, then x + y - y ought to return an object that is behaviorally equivalent to x. That means the two objects should ideally act like they have the same state.

You should provide mixed-mode arithmetic operators only when they make logical sense to users. For example, it makes sense to add a duration (say 35 days) to a date (say July 4, 1776), so you might define date + duration to return a Date. Similarly date - duration could also return a Date. But duration - date does not make sense at the conceptual level (what does it mean to subtract July 4, 1776 from 35 days?) so you should not define that operator.

If you provide constructive operators, they should return their result by value. For example, x + y should return its result by value.

If you provide constructive operators, they should not change their operands. For example, x + y should not change x. For some crazy reason, programmers often define x + y to be logically the same as x += y because the latter is faster. But remember, your users expect x + y to make a copy.

If you provide constructive operators, they should allow promotion of the left-hand operand. For example, if your class Fraction supports promotion from int to Fraction (via the non-explicit ctor Fraction::Fraction(int)), and if you allow x - y for two Fraction objects, you should also allow 42 - y. In practice that simply means that your operator-() should not be a member function of Fraction. Typically you will make it a friend, if for no other reason than to force it into the public: part of the class, but even if it is not a friend, it should not be a member.

In general, your operator should change its operand(s) if and only if the operands get changed when you apply the same operator to intrinsic types. x == y and x << y should not change either operand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Q: What is static_cast?

A

A: static_cast converts from a pointer to a base class to a pointer to its derived class, but does not perform type-safety checking.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Q: What is a conversion operator?

A

A: A class can have a public method for specific data type conversions. For example:

class Boo{
   double value;
  public: 
   Boo(int i );
   operator double() { return value; }};

Boo BooObject;
double i = BooObject;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Give the type for a function pointer to a static member function of Foo that returns int and takes char and float parameters.

A

A: int (*)(char,float)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Q: Can inline functions have a recursion?

A

A: No. Syntax wise it is allowed. But then the function is no longer Inline. As the compiler will never know how deep the recursion is at compilation time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Q: What is the default constructor?

A

A: A constructor with no arguments or one where all the arguments have default values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Q: What’s the order that objects in an array are destructed?

A

A: In reverse order of construction: First constructed, last destructed.In the following example, the order for destructors will be a[9], a[8], …, a[1], a[0]:

void userCode() {Fred a[10];}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Q: How can I make it so keys pressed by users are not echoed on the screen?

A

A: This is not a standard C++ feature. C++ doesn’t even require your system to have a keyboard or a screen. That means every operating system and vendor does it somewhat differently. Please read the documentation that came with your compiler for details on your particular installation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Q: Show a const object calling a const member.

A

A:

class Foo {
   int bar() const { return 99; }}

main…
const Foo f;
f.bar();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Q: What happens when a derived-class object is created and destroyed?

A

A: Space is allocated (on the stack or the heap) for the full object (that is, enough space to store the data members inherited from the base class plus the data members defined in the derived class). The base class’s constructor is called to initialize the data members inherited from the base class. The derived class’s constructor is then called to initialize the data members added in the derived class. The derived-class object is then usable.

When the object is destroyed (goes out of scope or is deleted) the derived class’s destructor is called on the object first. Then the base class’s destructor is called on the object. Finally the allocated space for the full object is reclaimed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Q: What is the difference between “new” and “operator new” ?

A

A: operator new (or new[]) allows the class designer to customize new(). Declaration looks like this:

class Myclass
 {
 public:
         void\* operator new(size\_t);
         void operator delete(void\*);
 };

One can implement new using malloc. The compiler takes care of creating the vtable and calling the constructor, so that isn’t done in the operator.

You can also call operator new like this:

::operator new(sizeof(Foo))

This calls the global operator new, which only allocates memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Q: What is a friend class?

A

A: A class that grants friend status to another class gives that class access rights to all private and protected members.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Q: How do you find the size of an integer data type with out using sizeof() function?

A

A:

int *i ;
int *j = i + 1;
cout << “ size of an integer variable i = “ << (int)j - (int)i << endl;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Q: Do friends violate encapsulation?

A

A: Not f they’re used properly, they enhance encapsulation.You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven’t increased the amount of code that needs direct access to a data structure; you’ve simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Q: Explain the statement, “friendship isn’t inherited, transitive, or reciprocal”?

A

A:

Inherited: Just because I grant you friendship access to me doesn’t automatically grant your kids access to me

Transitive: Just because I grant you friendship access to me doesn’t automatically grant your friends access to me

Transitive: Just because I grant you friendship access to me doesn’t automatically grant me access to you

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Q: Is it legal for a member function to say “delete this”?

A

A: As long as you’re careful, it’s OK for an object to commit suicide (delete this). Here’s how I define “careful”:

You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).

You must also be absolutely 100% positive sure that your member function will be the last member function invoked on this object.

47
Q

Q: What is a functor? Give an example of a C++ functor by overloading the function call ( ) operator.

A

A: Functors, or function objects, are objects that can be called like functions. They can be useful, for example, as callback functions. They have the advantage over functions in their power to retain state.

class Multiplier {
public:
Multiplier(int m): multiplier(m) {}
int operator()(int x) { return multiplier * x; }
private:
int multiplier;
};

Multiplier m(5);
 cout \<\< m(4) \<\< endl;
48
Q

Q: What should I catch?

A

A: In keeping with the C++ tradition of “there’s more than one way to do that” (translation: “give programmers options and tradeoffs so they can decide what’s best for them in their situation”), C++ allows you a variety of options for catching.You can catch by value.You can catch by reference.You can catch by pointer.

In fact, you have all the flexibility that you have in declaring function parameters, and the rules for whether a particular exception matches (i.e., will be caught by) a particular catch clause are almost exactly the same as the rules for parameter compatibility when calling a function.

Given all this flexibility, how do you decide what to catch? Simple: unless there’s a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer.

49
Q

Q: What does it mean to declare a…

(a) member function as virtual?
(b) member variable as static?
(c) function as static?
(d) destructor as static?

A

A:

(a) C++ virtual function is a member function of a class, whose functionality can be over- ridden in its derived classes. Non-virtual member functions are resolved at compile time, virtual member functions are resolved at run time.
(b) The static keyword allows a variable to maintain its value among different function calls. This is possible because, when the static variable is declared, the compiler uses a separate memory area to store it.
(c) A static member function can access only static member data, static member functions and data and functions outside the class. A static member function can be called even when a class is not instantiated. A static member function cannot be declared virtual. A static member function cannot have access to the ‘this’ pointer of the class.
(d) There is no such thing, unless “static destructor” means a static member function of the class that accepts a pointer to an object of that class that is to be destroyed.

50
Q

Q: Why should I use new instead of trustworthy old malloc()?

A

A: Constructors/destructors, type safety, overridability.

Constructors/destructors: unlike malloc(sizeof(Fred)), new Fred() calls Fred’s constructor. Similarly, delete p calls *p’s destructor.

Type safety: malloc() returns a void* which isn’t type safe. new Fred() returns a pointer of the right type (a Fred*).

Overridability: new is an operator that can be overridden by a class, while malloc() is not overridable on a per-class basis.

51
Q

Q: How can I provide printing for my class Fred?

A

include

A: Use operator overloading to provide a friend left-shift operator.

class Fred {
public:
friend std::ostream& operator<< (std::ostream& o, Fred const& fred);

private:
int i_; // Just for illustration
};

std::ostream& operator<< (std::ostream& o, Fred const& fred)
{
return o << fred.i_;
}

int main()
{
Fred f;
std::cout << “My Fred object: “ << f << “\n”;

}

We use a non-member function (a friend in this case) since the Fred object is the right-hand operand of the << operator.

53
Q

Q: What is a Polymorphic Class?

A

A: A polymorphic class contains at least one virtual method. C++ saves resources by create vtables only for polymorphic classes.

54
Q

Q: What is a smart pointer?

A

A: A smart pointer is a C++ class that mimics a regular pointer in syntax and some semantics, but it does more.

Because smart pointers to different types of objects tend to have a lot of code in common, almost all good-quality smart pointers in existence are templated by the pointee type.

This is the mantra of smart pointers: You can replace pointer definitions with smart pointer definitions without incurring major changes to your application’s code. You thus get extra goodies with ease. Minimizing code changes is very appealing and vital for getting large applications to use smart pointers.

55
Q

Q: What is Overriding?

A

A: To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.The definition of the method overriding is:· Must have same method name.· Must have same data type.· Must have same argument list. Overriding a method means that replacing a method functionality in child class.

57
Q

Q: Is there any problem with the following :

char*a=NULL;
char& p = *a;?

A

A: The result is undefined. You should never do this. A reference must always refer to some object.

58
Q

Q: What is encapsulation?

A

A: Containing and hiding Information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object’s operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data’s origin.

60
Q

Q: Which is better: NULL or 0?

A

A: In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That’s less common these days.

61
Q

Q: What is the difference between a copy constructor and an overloaded assignment operator?

A

A: 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.

They are defined separately, but copy may call assignment.

63
Q

Q: How the compiler arranges the various sections in the executable image?

A

A: The executable had following sections:

(a) Data Section (uninitialized data variable section, initialized data variable section )
(b) Code Section

Remember that all static variables are allocated in the initialized variable section.

64
Q

Q: When are copy constructors called?

A

A: Copy constructors are called in following cases:

(a) when a function returns an object of that class by value
(b) when the object of that class is passed by value as an argument to a function
(c) when you construct an object based on another object of the same class
(d) When compiler generates a temporary object

66
Q

Q: Can you use realloc() on pointers allocated via new?

A

A: No! When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves. They use their own copy constructor or assignment operator. Besides all that, the heap that new uses may not be the same as the heap that malloc() and realloc() use!

67
Q

Q: Can I explicitly call a destructor if I’ve allocated my object with new?

A

A: Probably not. Unless you used placement new, you should simply delete the object rather than explicitly calling the destructor, since doing so won’t release the memory that was allocated for the object itself. Remember: delete p does two things: it calls the destructor and it deallocates the memory.

68
Q

Q: What is a pure virtual function? What is an abstract class?

A

A: A function is a pure virtual function when you define only the function prototype in a base class without implementation and defer the complete implementation to a derived class. This base class is called an abstract class, and the client won’t able to instantiate an object using this base class. You can make a pure virtual function and abstract class this way:

class Boo{
   void foo() = 0;
 }

Boo MyBoo; // NO! compilation error

69
Q

Q: When you throw an object, how many times will it be copied?

A

A: Depends. Might be zero. Objects that are thrown must have a publicly accessible copy-constructor. The compiler is allowed to generate code that copies the thrown object any number of times. However even if the compiler never actually copies the thrown object, it must make sure the exception class’s copy constructor exists and is accessible.

70
Q

Q: What is the purpose of a ‘using’ declaration?

A

A: A using declaration makes it possible to use a name from a namespace without the scope (::) operator.

71
Q

Q: What does RTTI stand for?

A

A: Run Time Type Information

72
Q

Q: What is private?

A

A: Can be data or method member. They are private to the class where they are declared. Accessible ONLY by the member methods of the class where they are declared. Only exception to the above rule is Friend. In a C++ class, private is default for member declaration. That is, if you do not specify any access specifier (private, public, protected), the member is considered private.

73
Q

Q: What is the difference between memory allocation for these two codes:

MyClass* myClass = new MyClass();

myClass->MyField = “Hello world!”;

MyClass myClass;

myClass.MyField = “Hello world!”;

A

A: The first one uses the heap, the second one uses the stack.

74
Q

Q: What is Virtual Destructor?

A

A: Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism.

75
Q

Q: What is the significance of throw(…) in a method signature? Example:

int Gunc() throw();

int Hunc() throw(A,B);

A

A: Supposedly, throw() indicates a method may throw nothing while throw(A,B) indicates that the method may throw A or B.

This is not entirely the case at the moment. It is currently not common practice to use the method signature throw() idiom in C++.

77
Q

Q: Can you create operator** for “to-the-power-of” operations?

A

A: No. The names of, precedence of, associativity of, and arity of operators is fixed by the language. There is no operator** in C++, so you cannot create one for a class type.If you’re in doubt, consider that x ** y is the same as x * (*y) (in other words, the compiler assumes y is a pointer). Besides, operator overloading is just syntactic sugar for function calls. Although this particular syntactic sugar can be very sweet, it doesn’t add anything fundamental. I suggest you overload pow(base,exponent) (a double precision version is in ). By the way, operator^ can work for to-the-power-of, except it has the wrong precedence and associativity.

78
Q

Q: Is it possible to have Virtual Destructor? If yes, how? If not, Why not possible?

A

A: Yes there is a Virtual Destructor. A destructor can be virtua. The type of object the caller is calling to will determine the destructor will be called. Most destructors are virtual.

Parent destructors are automatically called in reverse order of construction.

79
Q

Q: What’s the order that local objects are destructed?

A

A: In reverse order of construction: First constructed, last destructed.In the following example, b’s destructor will be executed first, then a’s destructor:

void userCode() {Fred a;Fred b;… }

80
Q

Q: What function declaration syntax prevents it from throwing an exception?

A

A: type foo() throw();

May not throw exceptions. As opposed to

type foo();

Which can throw anything.

81
Q

Q: What is a constructor or ctor?

A

A: A constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.

81
Q

Q: What is a conversion constructor?

A

A constructor with a single argument is a conversion ctor and can be used for type conversion. For example:

class Boo {
public:
Boo( int i ); // conversion operator declaration
};

Boo BooObject = 10 ; // assigning int 10 Boo object

83
Q

Q: How do you call a member function on object o using function pointer f?

A

A:

o.*f();

You can create a macro to keep this readable. Note that pointers to member functions are meaningless without an object to operate on. Hence they cannot easily be used in straight C signal handlers etc. Pointers to static member functions can be used for this.

83
Q

Q: What is “placement new” and why would you use it?

A

A: There are many uses of placement new. The simplest use is to place an object at a particular location in memory. This is done by supplying the place as a pointer parameter to the new part of a new expression:

#include     
 #include "Fred.h" 
void someCode()
 {
   char memory[sizeof(Fred)];
   void\* place = memory;
   Fred\* f = new(place) Fred();
   // ... some time later
   f-\>~Fred();
 }

Note that you are responsible for memory alignment and for explicitly calling the destructor when the object’s lifetime ends.

84
Q

Q: How do I create a subscript operator for a Matrix class?

A

A: Use operator() rather than operator[].

When you have multiple subscripts, the cleanest way to do it is with operator() rather than with operator[]. The reason is that operator[] always takes exactly one parameter, but operator() can take any number of parameters.

85
Q

Q: Name two cases where you MUST use an initialization list as opposed to assignment in constructors.

A

A: Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.

86
Q

Q: What is a friend function?

A

A: A friend function is a non-member function which is declared as a friend in a class. When implemented, this function may access private areas of any such class passed to it.

88
Q

Q: Explain the scope resolution operator.

A

A: It 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.

90
Q

Q: Should you explicitly call a destructor on a local variable?

A

A: No! The destructor will get called again at the close } of the block in which the local was created. This is a guarantee of the language; it happens automagically; there’s no way to stop it from happening. But you can get really bad results from calling a destructor on the same object a second time! Bang! You’re dead!

91
Q

Q: What are all the implicit member functions of the class? Or what are all the functions that the compiler implements for us if we don’t define one?

A

A:

(a) default ctor
(b) copy ctor
(c) assignment operator
(d) default destructor
(e) address operator

92
Q

Q: What is passing by reference?

A

A: Method of passing arguments to a function which takes parameter of type reference. for example:

void swap( int & x, int &amp; y )
 {
 int temp = x;
 x = y;
 y = temp;
 }

Basically, inside the function there won’t be any copy of the arguments “x” and “y” instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.

93
Q

Q: What is a container class? What are the types of container classes?

A

A: A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows a great flexibility in the types supported as elements.

The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers).

Containers replicate structures very commonly used in programming: dynamic arrays (vector), queues (queue), stacks (stack), heaps (priority_queue), linked lists (list), trees (set), associative arrays (map)…

When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

94
Q

Q: What are the steps that happen in delete p?

A

A: delete p is a two-step process: it calls the destructor, then releases the memory. The code generated for delete p is functionally similar to this:

if (p != NULL) {
   p-\>~Fred();
   operator delete(p);
 }
94
Q

Q: When is a template a better solution than a base class?

A

A: 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 generality) to the designer of the container or manager class.

96
Q

Q: How do I allocate multidimensional arrays using new?

A

A: There are many ways to do this, depending on how flexible you want the array sizing to be. On one extreme, if you know all the dimensions at compile-time, you can allocate multidimensional arrays statically (as in C). No special delete is needed at function return, either.

More commonly, the size of the matrix isn’t known until run-time but you know that it will be rectangular. In this case you need to use the heap (“freestore”), but at least you are able to allocate all the elements in one freestore chunk. This means you will use a new Fred[nrows * ncols] and matching delete (even for exceptions).

Finally at the other extreme, you may not even be guaranteed that the matrix is rectangular. For example, if each row could have a different length, you’ll need to allocate each row individually.

97
Q

Q: In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?

A

A: No. If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantees that the memory sizeof(Fred) bytes that were allocated will automagically be released back to the heap.

99
Q

Q: What is the “Named Constructor Idiom”?

A

A: Also called a Factory. A technique that provides more intuitive and/or safer construction operations for users of your class. This also potentialy increases the number of possible ways to create an object. The nuber of proper constructors is limited by the restriction that each one must have different arguments. Factories do not have this limitation.

100
Q

Q: How can I “reopen” std::cin and std::cout in binary mode?

A

A: This is implementation dependent. Check with your compiler’s documentation.For example, suppose you want to do binary I/O using std::cin and std::cout.Unfortunately there is no standard way to cause std::cin, std::cout, and/or std::cerr to be opened in binary mode. Closing the streams and attempting to reopen them in binary mode might have unexpected or undesirable results.On systems where it makes a difference, the implementation might provide a way to make them binary streams, but you would have to check the implementation specifics to find out.

101
Q

Q: What is protected?

A

A:

* Can be data or method members

* Act exactly as private members for all practical purposes, so long as they are referenced from within the class (and/or instances of the class) where they are declared

* Specifically used to define how certain data/method members of a class would behave in a child class (used to define their behaviour in inheritance)

* The protected members become private of a child class in case of private inheritance, public in case of public inheritance, and stay protected in case of protected inheritance.

102
Q

Q: What problem does the namespace feature solve?

A

A: Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.

namespace [identifier] { namespace-body }

A namespace declaration identifies and assigns a name to a declarative region.The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.

103
Q

Q: What is an Iterator class?

A

A: A class that is used to traverse through the objects maintained by a container class.

There are several categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, and random access.

An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at- a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree).

The iterator is a construct which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class.

104
Q

Q: What is a nested class? Why can it be useful?

A

A: A nested class is a class enclosed within the scope of another class. For example:

  class OuterClass
   {
     class NestedClass
     {
     };
   };

Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass.

Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass’s members and friends can use NestedClass. When you instantiate an outer class, it won’t instantiate the inside class.

105
Q

Q: What is placement new?

A

A: Constructs an object at a specific location in memory.

106
Q

Q: Why should you use “const” reference arguments in a function?

A

A:

a) Using const protects you against programming errors that inadvertently alter data.
b) Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and use a temporary variable appropriately.

107
Q

Q: What can a derived class add?

A

A:

New data members

New member functions

New constructors and destructor

New friends

108
Q

Q: Should you use the this pointer in the constructor?

A

A: Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the {body} and even in the initialization list) if you are careful.

Here is something that always works: the {body} of a constructor (or a function called from the constructor) can reliably access the data members declared in a base class and/or the data members declared in the constructor’s own class.

Here is something that sometimes works: if you pass any of the data members in this object to another data member’s initializer, you must make sure that the other data member has already been initialized. You can determine whether the other data member has (or has not) been initialized using some straightforward language rules that are independent of the particular compiler you’re using.

109
Q

Q: What is typeid?

A

A: Keyword that returns a pointer to a std::type_info object with introspection info on the passed object. Can get class type, etc.

111
Q

Q: Give an example of composition through private inheritance and “using”. How is this different from public inheritance?

A

A:

class A {public void foo() {}} ;

class B : private A { using A::foo; }

This has the effect of giving B the public method foo. This allows us to cherry-pick methods, in contrast to public inheritance, which gives us all public methods.

111
Q

Q: What is public?

A

A:

* Can be data or method members

* Are accessible by any function/method/application globally, so long as an instance of the class where the public members are declared is created.

* These members are accessible only thru an instance of the class where they are declared

* Generally used to define a C++ class behavior and/or to access private data members (act as private data modifiers)

113
Q

Q: What is the difference between const char *myPointer and char *const myPointer?

A

A:

const char *myPointer

is a non constant pointer to constant data, while

char *const myPointer

is a constant pointer to non constant data.

114
Q

Q: What are inline functions? When are they used? How are they declared?

A

A: Inline functions have no linkage or call stack. Their code is simply inserted into the call point. They can be declared with the inline keyword at the declaration or definition point. They can also be implicitly declared by simply putting the method definition into the class declaration. Small methods are typically defined inline. Implicit default constructors are inline.

116
Q

Q: When are temporary variables created by C++ compiler?

A

A: Temprovary variables are created on the stack by the compiler and are used during reference initialization and during evaluation of expressions including standard type conversions, argument passing, function returns.

Here are two examples using fundamental types:

a) The actual argument is the correct type, but it isn’t an Lvalue:

double Cube(const double & num){
 num = num \* num \* num;
 return num; }
double temp = 2.0;
 double value = cube(3.0 + temp);
 // argument is a expression and not a Lvalue

b) The actual argument is of the wrong type, but of a type that can be converted to the correct type

long temp = 3L;
 double value = cuberoot ( temp);
 // long to double conversion
116
Q

Q: Which types of members will cause the compiler not to generate an implicit constructor?

A

A: Any const or reference members.

117
Q

Q: What is the preferred way to create custom exceptions?

A

A: Subclass std class “exception” and override what().

119
Q

Q: Which constructor gets called when you create an array of n Fred objects?

A

A: Fred’s default constructor gets called n times.

If your class doesn’t have a default constructor, you’ll get a compile-time error when you attempt to create an array using the default syntax,

However, even if your class already has a default constructor, you should try to use std::vector rather than an array (arrays are evil). std::vector lets you decide to use any constructor, not just the default constructor:

std::vector a(10, Fred(5,7));

120
Q

Q: What is dynamic_cast?

A

A: dynamic_cast performs type safety check at runtime, and if the types are not compatible, an exception will be thrown (when dealing with references) or a null pointer will be returned (when dealing with pointers).

122
Q

Q: What is an auto pointer?

A

A: auto_ptr is the simplest example of a smart pointer, and is included in the standard C++ library.

auto_ptr attempts to resolve problems with memory leaks and dangling pointers.

123
Q

Q: How do you access the static member of a class?

A

A: Use the :: operator ala Foo::member

124
Q

Q: What is an abstract class?

A

A: A class containing at least one pure virtual function. And abstract class cannot be used as a parameter type, return type, or in an explicit conversion. You cannot instantiate an abstract class. You can create pointers and references to abstract classes.

125
Q

Q: What is the difference between malloc()/free() and new/delete?

A

A: malloc allocates memory for the object in heap but doesn’t invoke object’s constructor to initialize the object. new allocates memory and also invokes constructor to initialize the object. malloc() and free() do not support object semantics and do not construct or destruct objects.

126
Q

Q: What is name mangling in C++??

A

A: The process of encoding the parameter types with the function/method name into a unique name is called name mangling. The inverse process is called demangling.For example Foo::bar(int, long) const is mangled as ‘bar__C3Fooil’.For a constructor, the method name is left out.That is Foo::Foo(int, long) const is mangled as ‘C3Fooil’

127
Q

Q: How can I provide printing for an entire hierarchy of classes?

A

A: Provide a friend operator<< that calls a protected virtual function:

class Base {
 public:
 friend std::ostream& operator\<\< (std::ostream& o, const Base& b);
 protected:
 virtual void printOn(std::ostream& o) const;
 };
 inline std::ostream& operator\<\< (std::ostream& o, const Base& b)
 {
 b.printOn(o);
 return o;
 }
 class Derived : public Base {
 protected:virtual void printOn(std::ostream& o) const;
 };

The end result is that operator<< acts as if it were dynamically bound, even though it’s a friend function. This is called the Virtual Friend Function Idiom. Note that derived classes override printOn(std::ostream&) const. In particular, they do not provide their own operator< syntax!

128
Q

Q: Where did this wonderful stack of flashcards come from?

A

A: Mike Johnson can take the blame, but not the credit. Many of these Q’s and A’s came from the C++ online FAQ. See http://www.parashift.com/c++-faq. Some of them came from Gotw.ca. Some of them came from StackOverflow.com. Some of them are used without attribution (copyright requires substantial creative content, so I’m hopefully legally right to pull technical facts from the web).

Generous rewording and opining have been done by Mike.

If you got this one wrong, please reset all flashcards to zero and start over studying from scratch. ;)

129
Q

Q: What is the order of implicit conversion in binary operators for fundamental types?

A

A: If either is long double the other is promoted to long double.

The same goes in order for
double,
float,
long long unsigned int,
long long int,
long unsigned int,
long,
unsigned int,
int

Otherwise, both operators are promoted to int. Note that some of these conversions cause a loss of precision.

130
Q

Q: How do I throw polymorphically?

A

A: Sometimes people write code like:

class MyExceptionBase { };

class MyExceptionDerived : public MyExceptionBase { };

void f(MyExceptionBase& e)
 {  throw e; }
void g()
 {
   MyExceptionDerived e;
   try {
     f(e);
   }
   catch (MyExceptionDerived& e) {
     ...code to handle MyExceptionDerived...
   }
   catch (...) {
     ...code to handle other exceptions...
   }

}

If you try this, you might be surprised at run-time when your catch (…) clause is entered, and not your catch (MyExceptionDerived&) clause. This happens because you didn’t throw polymorphically. In function f(), the statement throw e; throws an object with the same type as the static type of the expression e. In other words, it throws an instance of MyExceptionBase. The throw statement behaves as-if the thrown object is copied, as opposed to making a “virtual copy”.

Fortunately it’s relatively easy to correct:

class MyExceptionBase {
 public:
   virtual void raise();
 };

void MyExceptionBase::raise()
{ throw *this; }

class MyExceptionDerived : public MyExceptionBase {
 public:
   virtual void raise();
 };

void MyExceptionDerived::raise()
{ throw *this; }

void f(MyExceptionBase& e)
 {
   // ...
   e.raise();
 }
void g()
 {
   MyExceptionDerived e;
   try {
     f(e);
   }
   catch (MyExceptionDerived& e) {
     ...code to handle MyExceptionDerived...
   }
   catch (...) {
     ...code to handle other exceptions...
   }
 }

Note that the throw statement has been moved into a virtual function. The statement e.raise() will exhibit polymorphic behavior, since raise() is declared virtual and e was passed by reference. As before, the thrown object will be of the static type of the argument in the throw statement, but within MyExceptionDerived::raise(), that static type is MyExceptionDerived, not MyExceptionBase.

132
Q

Q: How virtual functions are implemented by the C++ compiler?

A

A: Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in a class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions

133
Q

Q: What are some debugging methods?

A

A: Debugging with tools like :

(a) GDB, DBG, Forte, Visual Studio.
(b) Analyzing the Core dump.
(c) Using dtrace to trace the last system call before crash.
(d) Putting debug statements in the program source code.

134
Q

Q: Is it possible to have Virtual Constructor? How and/or why?

A

A: There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructoris a code which is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

135
Q

Q: When is a constructor trivial?

A

A:

A() is implicitly defined. class A has no virtual functions and no virtual base classes. All the direct base classes of A have trivial constructors. The classes of all the nonstatic data members of A have trivial constructors.

Trivial constructors are not synthesized by the compiler.

136
Q

Q: Give the type for a function pointer to a function that returns int and takes char and float parameters.

A

A: int (*)(char,float)

137
Q

Q: Can you free() pointers allocated with new? Can you delete pointers allocated with malloc()?

A

A: No! It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program. But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc(). Mixing these up could cause a catastrophic failure at runtime. You have been warned.

138
Q

Q: What does

extern “C” int func(int *, Foo)

accomplish?

A

A: It will turn off name mangling for func so that one can link to code compiled by a C compiler. Name mangling is used by C++ to support function overloading, even for functions which are not class members.

139
Q

Q: What is a rule of thumb for preferring references over pointers

A

A: Use pointers when you need to do pointer arithmetic or have NULL values, otherwise use references.

140
Q

Q: How do you handle a destructor that fails?

A

A: Write a message to a log, but do not throw an exception.

The C++ rule is that you must never throw an exception from a destructor that is being called during the “stack unwinding” process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding. During stack unwinding, all the local objects in allthose stack frames are destructed. If one of those destructors throws an exception the C++ runtime system doesn’t know what to do.

141
Q

Q: Can you overload a function based only on whether a parameter is a value or a reference?

A

A: No. Passing by value and by reference looks identical to the caller.

142
Q

Q: What is the difference between a pointer and a reference?

A

A: 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.

143
Q

Q: How can I open a stream in binary mode?

A

A: Use std::ios::binary. Some operating systems differentiate between text and binary modes. In text mode, end-of-line sequences and possibly other things are translated; in binary mode, they are not. For example, in text mode under Windows, “\r\n” is translated into “\n” on input, and the reverse on output.To read a file in binary mode, use something like this:

void readBinaryFile(const std::string& filename)
{
std::ifstream input(filename.c_str(), std::ios::in | std::ios::binary);
char c;
while (input.get(c))
{…do something with c here…}}

Note: input >> c discards leading whitespace, so you won’t normally use that when reading binary files.

144
Q

Q: What is a reference?

A

A: reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object. Prepending a variable with “&” symbol makes it a reference. For example:

int a;
int &b = a;

References cannot change their referee, ever. Assignments such as a=b will copy object values.