Saturday, May 31, 2008

Given you the promised sutff. Didnt I

I now need some serious feedback , Since I have given a lot of puzzles and C and C++ questions out. Do you think it is a good idea to do post out my collection to the web for Ruby, PHP , UNIX, python and porting stuff,

If I am not able to garner enough feedback I might at a loss here.

happy interviewing guys. This time around no body will have any questions left for you to answer , I am sure.

Also send me mails in case you have doubts about any of them. My email id is right there on the top right corner of this webpage.

Hope to see you returning for more updates on my site

Unknown C more and more and even more

Write a small C program to determine whether a machine's type is little-endian or big-endian. The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work.

#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}

Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three. What's the mistake in the following code?

#include <stdio.h>
int main()
{
int* ptr1,ptr2;
ptr1 = (int*)malloc(sizeof(int));
ptr2 = ptr1;
*ptr2 = 10;
return 0;
}

What is the output of the following program?

#include <stdio.h>
int main()
{
int cnt = 5, a;

do {
a /= cnt;
} while (cnt --);

printf ("%d\n", a);
return 0;
}

What is the output of the following program?

#include <stdio.h>
int main()
{
int i = 6;
if( ((++i < 7) && ( i++/6)) || (++i <= 9))
;
printf("%d\n",i);
return 0;
}

What is the bug in the following program?

#include <stdlib.h>
#include <stdio.h>
#define SIZE 15
int main()
{
int *a, i;

a = (int*) malloc(SIZE*sizeof(int));

for (i=0; i<SIZE; i++)
*(a + i) = i * i;
for (i=0; i<SIZE; i++)
printf("%d\n", *a++);
free(a);
return 0;
}

Is the following a valid C program? If so, what is the output of it?

#include <stdio.h>
int main()
{
int a=3, b = 5;

printf(&a["Ya!Hello! how is this? %s\n"], &b["junk/super"]);
printf(&a["WHAT%c%c%c %c%c %c !\n"], 1["this"],
2["beauty"],0["tool"],0["is"],3["sensitive"],4["CCCCCC"]);
return 0;
}

Write a C program which prints Hello World! without using a semicolon!!! What is the output of the following, if the input provided is:
Life is beautiful

#include <stdio.h>
int main()
{
char dummy[80];
printf("Enter a string:\n");
scanf("%[^a]",dummy);
printf("%s\n",dummy);
return 0;
}

Write a C program to find the smallest of three integers, without using any of the comparision operators.

Unknown C more and more

The following is the offset macros which is used many a times. Figure out what is it trying to do and what is the advantage of using it.

#define offsetof(a,b) ((int)(&(((a*)(0))->b)))

The following is the macro implementation of the famous, Triple xor swap.

#define SWAP(a,b) ((a) ^= (b) ^= (a) ^= (b))

What are the potential problems with the above macro? What does the format specifier %n of printf function do? What is the use of the following macro?

#define DPRINTF(x) printf("%s:%d\n",#x,x)

Let's say you were asked to code a function IAddOverFlow which takes three parameters, pointer to an integer where the result is to be stored, and the two integers which needs to be added. It returns 0 if there is an overflow and 1 otherwise:

int IAddOverFlow(int* result,int a,int b)
{
/* ... */
}

So, how do you code the above function? (To put in a nutshell, what is the logic you use for overflow detection?) What does the following macro do?

#define ROUNDUP(x,n) ((x+n-1)&(~(n-1)))

Most of the C programming books, give the following example for the definition of macros.

#define isupper(c) (((c) >= 'A') && ((c) <= 'Z'))

But there would be a serious problem with the above definition of macro, if it is used as follows (what is the problem??)

char c;
/* ... */
if(isupper(c++))
{
/* ... */
}

But most of the libraries implement the isupper (declared in ctypes.h) as a macro (without any side effects). Find out how isupper() is implemented on your system. What is the output of the following program?

#include <stdio.h>
#include <stdlib.h>

#define SIZEOF(arr) (sizeof(arr)/sizeof(arr[0]))

#define PrintInt(expr) printf("%s:%d\n",#expr,(expr))
int main()
{
/* The powers of 10 */
int pot[] = {
0001,
0010,
0100,
1000
};
int i;

for(i=0;i<SIZEOF(pot);i++)
PrintInt(pot[i]);
return 0;
}

The following is the implementation of the Euclid's algorithm for finding the G.C.D(Greatest Common divisor) of two integers. Explain the logic for the below implementation and think of any possible improvements on the current implementation.
BTW, what does scanf function return?

#include <stdio.h>
int gcd(int u,int v)
{
int t;
while(v > 0)
{
if(u > v)
{
t = u;
u = v;
v = t;
}
v = v-u;
}
return u;
}

int main()
{
int x,y;
printf("Enter x y to find their gcd:");
while(scanf("%d%d",&x, &y) != EOF)
{
if(x >0 && y>0)
printf("%d %d %d\n",x,y,gcd(x,y));
printf("Enter x y to find their gcd:");
}
printf("\n");
return 0;
}

Also implement a C function similar to the above to find the GCD of 4 integers. I hope you know that ellipsis (...) is used to specify variable number of arguments to a function. (What is the function prototype declaration for printf?) What is wrong with the following delcaration?

int VarArguments(...)
{
/*....*/
return 0;
}

Write a C function which does the addition of two integers without using the '+' operator. You can use only the bitwise operators.(Remember the good old method of implementing the full-adder circuit using the or, and, xor gates....) How do you print I can print % using the printf function? (Remember % is used as a format specifier!!!) What's the output of the following program. (No, it's not 10!!!)

#include <stdio.h>
#define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
int main()
{
int y = 100;
int *p;
p = (int*)malloc(sizeof(int));
*p = 10;
y = y/*p; /*dividing y by *p */;
PrintInt(y);
return 0;
}

What's the difference between the following two C statements?

const char *p;
char* const p;

What is the difference between memcpy and memmove? What is the format specifiers for printf to print double and float values? The following is a simple C program to read a date and print the date. Run it and explain the behaviour

#include <stdio.h>
int main()
{
int day,month,year;
printf("Enter the date (dd-mm-yyyy) format including -'s:");
scanf("%d-%d-%d",&day,&month,&year);
printf("The date you have entered is %d-%d-%d\n",day,month,year);
return 0;
}

The following is a simple C program to read and print an integer. But it is not working properly. What is(are) the mistake(s)?

#include <stdio.h>
int main()
{
int n;
printf("Enter a number:\n");
scanf("%d\n",n);

printf("You entered %d \n",n);
return 0;
}

The following is a simple C program which tries to multiply an integer by 5 using the bitwise operations. But it doesn't do so. Explain the reason for the wrong behaviour of the program.

#include <stdio.h>
#define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
int FiveTimes(int a)
{
int t;
t = a<<2 + a;
return t;
}

int main()
{
int a = 1, b = 2,c = 3;
PrintInt(FiveTimes(a));
PrintInt(FiveTimes(b));
PrintInt(FiveTimes(c));
return 0;
}

Is the following a valid C program?

#include <stdio.h>
#define PrintInt(expr) printf("%s : %d\n",#expr,(expr))
int max(int x, int y)
{
(x > y) ? return x : return y;
}

int main()
{
int a = 10, b = 20;
PrintInt(a);
PrintInt(b);
PrintInt(max(a,b));
}

Unknown C more

Operators Can Only be Overloaded for User-Defined Types
An overloaded operator must take at least one argument of a user-defined type (operators new and delete are an exception). This rule ensures that users cannot alter the meaning of expressions that contain only fundamental types. For example:

int i,j,k;
k = i + j; //always uses built-in = and +
Recall that enum types are user-defined types, and as such, you can define overloaded operators for them too.
Overloaded Operators May Not Have Default Parameters
Unlike ordinary functions, overloaded operators cannot declare a parameter with a default value (overloaded operator() is the only exception):

class Date
{
private:
int day, month, year;
public:
Date & operator += (const Date & d = Date() ); //error, default arguments are not allowed
};
This rule may seem arbitrary. However, it captures the behavior of built-in operators, which never have default operands either.

Member and Non-Member Overloaded Operators
Most of the overloaded operators can be declared either as non-static class members or as non-member functions. In this example, operator == is overloaded as a non-static class member:

class Date{
//…
public:
bool operator == (const Date & d ); // 1: member function
};

Alternatively, one can declare it as a friend function:

bool operator ==( const Date & d1, const Date& d2); // 2: extern function
class Date{
friend bool operator ==( const Date & d1, const Date& d2);
};
Nonetheless, the operators [], (), = and ->can only be declared as non-static member functions. This ensures that their first operand is a l-value.

Overloading Operators for enum Types
For some enum types, it may be useful to define overloaded operators, such as ++ and --, that can iterate through the enumerator values:

#include <iostream>
using namespace std;

enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

Days& operator++(Days& d, int) // int denotes postfix++
{
if (d == Sun) return d = Mon; //rollover
int temp = d;
return d = static_cast<Days> (++temp);
}

int main()
{
Days day = Mon;
for (;;) //display days as integers
{
cout<< day <<endl;
day++;
if (day == Mon) break;
}
return 0;
}
Overload New and Delete in a Class
It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:

#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
C();
void* operator new (size_t size); //implicitly declared as a static member function
void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t size) throw (const char *){
void * p = malloc(size);
if (p == 0) throw "allocation failure"; //instead of std::bad_alloc
return p;
}

void C::operator delete (void *p){
C* pc = static_cast<C*>(p);
free(p);
}

int main() {
C *p = new C; // calls C::new
delete p; // calls C::delete
}
Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
Operator overloading rules of thumb
When overloading an operator to support a user-defined type (object), it is best to adhere to the basic semantics of that built-in operator. For instance, the built-in operator ==, which does not modify any of its operands, should also be overloaded in such a way that it does not modify any of its operands (and should be declared as a const member function, as a matter of fact). On the other hand, operators such as + =, which do modify their left operand, should be overloaded in a way that reflects that, i.e., by changing their objects. Note that in many cases, the implementer's code (e.g, a commercial library package) may not (and should not) be accessible to its user, so overloading an operator in an unexpected, unintuitive manner is not recommended.
class Date{
int day, month, year;
Date();
//...
public:
bool operator == (const Date & d) const; //none of the operands //is changed

Date & operator += (const Date & d); //builtin += does change //its left operand but not //its right one when //applied to numerals; the //same behavior is //maintained here.
One more thing to remember when defining copy constructor and operator=
Assigning an object to itself is disastrous, so whenever you have to define a copy constructor and assignment operator, make sure your code is guarded from such a mistake:

class Date {
int day, month, year;
//...
Date & operator= (const Date & other){ *this=other; //Dangerous
return *this;}
//...
}
void f () {
Date d;
Date *pdate = &d;

//...many lines of code

*pdate=d; //oops, object assigned to itself; disastrous
}//f()
A safe version should look like this:

Date & Date::operator= (const Date & other)
{
if (&other != this) //guarded from self assignment
{
*this = other;
//...
}

return *this;
}

Overloading postfix and prefix ++
For primitive types the C++ language distinguishes between ++x; and x++; as well as between --x; and x--; For objects requiring a distinction between prefix and postfix overloaded operators, the following rule is used:

class Date {
//...
public:
Date& operator++(); //prefix
Date& operator--(); //prefix
Date& operator++(int unused); //postfix
Date& operator--(int unused); //postfix
};
Postfix operators are declared with a dummy int argument (which is ignored) in order to distinguish them from the prefix operators, which take no arguments:

void f()
{
Date d, d1;
d1 = ++d;//prefix: first increment d and then assign to d1
d1 = d++; //postfix; first assign, increment d afterwards
}
Assignment operator is not inherited
Unlike ordinary base class member functions, assignment operator is not inherited. It may be re-defined by the implementer of the derived class or else it is automatically synthesized by the compiler, so there's not much point in declaring it virtual.

Hiding a base class member function
A derived class may hide a member function declared in its base class by using the same function name, but with a different signature, or list of arguments. Usually, this case suggests a programmer's mistake, especially if the hidden function is virtual. However, it can also be used as a means of hiding a base class member function when the designer of the derived class decides that any invocation of the original member function is undesirable or even dangerous:

class B {
private:
FILE *pf;
public:
//...
virtual void close(FILE *f) //may throw an exception
};

class D : public B { //no file I/O in D, calling B::close from
//here is dangerous and never needed.
public:
//a 'neutralized' close, harmless
void close(int i){} //hiding B::close(), not overriding it
};


void f()
{
B b;
FILE *p;
//....
D d;
d.close(p);//compile-time error: B::close()not accessible

}

Some quick C ones that I dont have answers of

Operators Can Only be Overloaded for User-Defined Types
An overloaded operator must take at least one argument of a user-defined type (operators new and delete are an exception). This rule ensures that users cannot alter the meaning of expressions that contain only fundamental types. For example:

int i,j,k;
k = i + j; //always uses built-in = and +
Recall that enum types are user-defined types, and as such, you can define overloaded operators for them too.
Overloaded Operators May Not Have Default Parameters
Unlike ordinary functions, overloaded operators cannot declare a parameter with a default value (overloaded operator() is the only exception):

class Date
{
private:
int day, month, year;
public:
Date & operator += (const Date & d = Date() ); //error, default arguments are not allowed
};
This rule may seem arbitrary. However, it captures the behavior of built-in operators, which never have default operands either.

Member and Non-Member Overloaded Operators
Most of the overloaded operators can be declared either as non-static class members or as non-member functions. In this example, operator == is overloaded as a non-static class member:

class Date{
//…
public:
bool operator == (const Date & d ); // 1: member function
};

Alternatively, one can declare it as a friend function:

bool operator ==( const Date & d1, const Date& d2); // 2: extern function
class Date{
friend bool operator ==( const Date & d1, const Date& d2);
};
Nonetheless, the operators [], (), = and ->can only be declared as non-static member functions. This ensures that their first operand is a l-value.

Overloading Operators for enum Types
For some enum types, it may be useful to define overloaded operators, such as ++ and --, that can iterate through the enumerator values:

#include <iostream>
using namespace std;

enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

Days& operator++(Days& d, int) // int denotes postfix++
{
if (d == Sun) return d = Mon; //rollover
int temp = d;
return d = static_cast<Days> (++temp);
}

int main()
{
Days day = Mon;
for (;;) //display days as integers
{
cout<< day <<endl;
day++;
if (day == Mon) break;
}
return 0;
}
Overload New and Delete in a Class
It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:

#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
C();
void* operator new (size_t size); //implicitly declared as a static member function
void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t size) throw (const char *){
void * p = malloc(size);
if (p == 0) throw "allocation failure"; //instead of std::bad_alloc
return p;
}

void C::operator delete (void *p){
C* pc = static_cast<C*>(p);
free(p);
}

int main() {
C *p = new C; // calls C::new
delete p; // calls C::delete
}
Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
Operator overloading rules of thumb
When overloading an operator to support a user-defined type (object), it is best to adhere to the basic semantics of that built-in operator. For instance, the built-in operator ==, which does not modify any of its operands, should also be overloaded in such a way that it does not modify any of its operands (and should be declared as a const member function, as a matter of fact). On the other hand, operators such as + =, which do modify their left operand, should be overloaded in a way that reflects that, i.e., by changing their objects. Note that in many cases, the implementer's code (e.g, a commercial library package) may not (and should not) be accessible to its user, so overloading an operator in an unexpected, unintuitive manner is not recommended.
class Date{
int day, month, year;
Date();
//...
public:
bool operator == (const Date & d) const; //none of the operands //is changed

Date & operator += (const Date & d); //builtin += does change //its left operand but not //its right one when //applied to numerals; the //same behavior is //maintained here.
One more thing to remember when defining copy constructor and operator=
Assigning an object to itself is disastrous, so whenever you have to define a copy constructor and assignment operator, make sure your code is guarded from such a mistake:

class Date {
int day, month, year;
//...
Date & operator= (const Date & other){ *this=other; //Dangerous
return *this;}
//...
}
void f () {
Date d;
Date *pdate = &d;

//...many lines of code

*pdate=d; //oops, object assigned to itself; disastrous
}//f()
A safe version should look like this:

Date & Date::operator= (const Date & other)
{
if (&other != this) //guarded from self assignment
{
*this = other;
//...
}

return *this;
}

Overloading postfix and prefix ++
For primitive types the C++ language distinguishes between ++x; and x++; as well as between --x; and x--; For objects requiring a distinction between prefix and postfix overloaded operators, the following rule is used:

class Date {
//...
public:
Date& operator++(); //prefix
Date& operator--(); //prefix
Date& operator++(int unused); //postfix
Date& operator--(int unused); //postfix
};
Postfix operators are declared with a dummy int argument (which is ignored) in order to distinguish them from the prefix operators, which take no arguments:

void f()
{
Date d, d1;
d1 = ++d;//prefix: first increment d and then assign to d1
d1 = d++; //postfix; first assign, increment d afterwards
}
Assignment operator is not inherited
Unlike ordinary base class member functions, assignment operator is not inherited. It may be re-defined by the implementer of the derived class or else it is automatically synthesized by the compiler, so there's not much point in declaring it virtual.

Hiding a base class member function
A derived class may hide a member function declared in its base class by using the same function name, but with a different signature, or list of arguments. Usually, this case suggests a programmer's mistake, especially if the hidden function is virtual. However, it can also be used as a means of hiding a base class member function when the designer of the derived class decides that any invocation of the original member function is undesirable or even dangerous:

class B {
private:
FILE *pf;
public:
//...
virtual void close(FILE *f) //may throw an exception
};

class D : public B { //no file I/O in D, calling B::close from
//here is dangerous and never needed.
public:
//a 'neutralized' close, harmless
void close(int i){} //hiding B::close(), not overriding it
};


void f()
{
B b;
FILE *p;
//....
D d;
d.close(p);//compile-time error: B::close()not accessible

}

C++ #30

Operators Can Only be Overloaded for User-Defined Types
An overloaded operator must take at least one argument of a user-defined type (operators new and delete are an exception). This rule ensures that users cannot alter the meaning of expressions that contain only fundamental types. For example:

int i,j,k;
k = i + j; //always uses built-in = and +
Recall that enum types are user-defined types, and as such, you can define overloaded operators for them too.
Overloaded Operators May Not Have Default Parameters
Unlike ordinary functions, overloaded operators cannot declare a parameter with a default value (overloaded operator() is the only exception):

class Date
{
private:
int day, month, year;
public:
Date & operator += (const Date & d = Date() ); //error, default arguments are not allowed
};
This rule may seem arbitrary. However, it captures the behavior of built-in operators, which never have default operands either.

Member and Non-Member Overloaded Operators
Most of the overloaded operators can be declared either as non-static class members or as non-member functions. In this example, operator == is overloaded as a non-static class member:

class Date{
//…
public:
bool operator == (const Date & d ); // 1: member function
};

Alternatively, one can declare it as a friend function:

bool operator ==( const Date & d1, const Date& d2); // 2: extern function
class Date{
friend bool operator ==( const Date & d1, const Date& d2);
};
Nonetheless, the operators [], (), = and ->can only be declared as non-static member functions. This ensures that their first operand is a l-value.

Overloading Operators for enum Types
For some enum types, it may be useful to define overloaded operators, such as ++ and --, that can iterate through the enumerator values:

#include <iostream>
using namespace std;

enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

Days& operator++(Days& d, int) // int denotes postfix++
{
if (d == Sun) return d = Mon; //rollover
int temp = d;
return d = static_cast<Days> (++temp);
}

int main()
{
Days day = Mon;
for (;;) //display days as integers
{
cout<< day <<endl;
day++;
if (day == Mon) break;
}
return 0;
}
Overload New and Delete in a Class
It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:

#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
C();
void* operator new (size_t size); //implicitly declared as a static member function
void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t size) throw (const char *){
void * p = malloc(size);
if (p == 0) throw "allocation failure"; //instead of std::bad_alloc
return p;
}

void C::operator delete (void *p){
C* pc = static_cast<C*>(p);
free(p);
}

int main() {
C *p = new C; // calls C::new
delete p; // calls C::delete
}
Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
Operator overloading rules of thumb
When overloading an operator to support a user-defined type (object), it is best to adhere to the basic semantics of that built-in operator. For instance, the built-in operator ==, which does not modify any of its operands, should also be overloaded in such a way that it does not modify any of its operands (and should be declared as a const member function, as a matter of fact). On the other hand, operators such as + =, which do modify their left operand, should be overloaded in a way that reflects that, i.e., by changing their objects. Note that in many cases, the implementer's code (e.g, a commercial library package) may not (and should not) be accessible to its user, so overloading an operator in an unexpected, unintuitive manner is not recommended.
class Date{
int day, month, year;
Date();
//...
public:
bool operator == (const Date & d) const; //none of the operands //is changed

Date & operator += (const Date & d); //builtin += does change //its left operand but not //its right one when //applied to numerals; the //same behavior is //maintained here.
One more thing to remember when defining copy constructor and operator=
Assigning an object to itself is disastrous, so whenever you have to define a copy constructor and assignment operator, make sure your code is guarded from such a mistake:

class Date {
int day, month, year;
//...
Date & operator= (const Date & other){ *this=other; //Dangerous
return *this;}
//...
}
void f () {
Date d;
Date *pdate = &d;

//...many lines of code

*pdate=d; //oops, object assigned to itself; disastrous
}//f()
A safe version should look like this:

Date & Date::operator= (const Date & other)
{
if (&other != this) //guarded from self assignment
{
*this = other;
//...
}

return *this;
}

Overloading postfix and prefix ++
For primitive types the C++ language distinguishes between ++x; and x++; as well as between --x; and x--; For objects requiring a distinction between prefix and postfix overloaded operators, the following rule is used:

class Date {
//...
public:
Date& operator++(); //prefix
Date& operator--(); //prefix
Date& operator++(int unused); //postfix
Date& operator--(int unused); //postfix
};
Postfix operators are declared with a dummy int argument (which is ignored) in order to distinguish them from the prefix operators, which take no arguments:

void f()
{
Date d, d1;
d1 = ++d;//prefix: first increment d and then assign to d1
d1 = d++; //postfix; first assign, increment d afterwards
}
Assignment operator is not inherited
Unlike ordinary base class member functions, assignment operator is not inherited. It may be re-defined by the implementer of the derived class or else it is automatically synthesized by the compiler, so there's not much point in declaring it virtual.

Hiding a base class member function
A derived class may hide a member function declared in its base class by using the same function name, but with a different signature, or list of arguments. Usually, this case suggests a programmer's mistake, especially if the hidden function is virtual. However, it can also be used as a means of hiding a base class member function when the designer of the derived class decides that any invocation of the original member function is undesirable or even dangerous:

class B {
private:
FILE *pf;
public:
//...
virtual void close(FILE *f) //may throw an exception
};

class D : public B { //no file I/O in D, calling B::close from
//here is dangerous and never needed.
public:
//a 'neutralized' close, harmless
void close(int i){} //hiding B::close(), not overriding it
};


void f()
{
B b;
FILE *p;
//....
D d;
d.close(p);//compile-time error: B::close()not accessible

}

C++ #29

Operators Can Only be Overloaded for User-Defined Types
An overloaded operator must take at least one argument of a user-defined type (operators new and delete are an exception). This rule ensures that users cannot alter the meaning of expressions that contain only fundamental types. For example:

int i,j,k;
k = i + j; //always uses built-in = and +
Recall that enum types are user-defined types, and as such, you can define overloaded operators for them too.
Overloaded Operators May Not Have Default Parameters
Unlike ordinary functions, overloaded operators cannot declare a parameter with a default value (overloaded operator() is the only exception):

class Date
{
private:
int day, month, year;
public:
Date & operator += (const Date & d = Date() ); //error, default arguments are not allowed
};
This rule may seem arbitrary. However, it captures the behavior of built-in operators, which never have default operands either.

Member and Non-Member Overloaded Operators
Most of the overloaded operators can be declared either as non-static class members or as non-member functions. In this example, operator == is overloaded as a non-static class member:

class Date{
//…
public:
bool operator == (const Date & d ); // 1: member function
};

Alternatively, one can declare it as a friend function:

bool operator ==( const Date & d1, const Date& d2); // 2: extern function
class Date{
friend bool operator ==( const Date & d1, const Date& d2);
};
Nonetheless, the operators [], (), = and ->can only be declared as non-static member functions. This ensures that their first operand is a l-value.

Overloading Operators for enum Types
For some enum types, it may be useful to define overloaded operators, such as ++ and --, that can iterate through the enumerator values:

#include <iostream>
using namespace std;

enum Days {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

Days& operator++(Days& d, int) // int denotes postfix++
{
if (d == Sun) return d = Mon; //rollover
int temp = d;
return d = static_cast<Days> (++temp);
}

int main()
{
Days day = Mon;
for (;;) //display days as integers
{
cout<< day <<endl;
day++;
if (day == Mon) break;
}
return 0;
}
Overload New and Delete in a Class
It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:

#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
C();
void* operator new (size_t size); //implicitly declared as a static member function
void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t size) throw (const char *){
void * p = malloc(size);
if (p == 0) throw "allocation failure"; //instead of std::bad_alloc
return p;
}

void C::operator delete (void *p){
C* pc = static_cast<C*>(p);
free(p);
}

int main() {
C *p = new C; // calls C::new
delete p; // calls C::delete
}
Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
Operator overloading rules of thumb
When overloading an operator to support a user-defined type (object), it is best to adhere to the basic semantics of that built-in operator. For instance, the built-in operator ==, which does not modify any of its operands, should also be overloaded in such a way that it does not modify any of its operands (and should be declared as a const member function, as a matter of fact). On the other hand, operators such as + =, which do modify their left operand, should be overloaded in a way that reflects that, i.e., by changing their objects. Note that in many cases, the implementer's code (e.g, a commercial library package) may not (and should not) be accessible to its user, so overloading an operator in an unexpected, unintuitive manner is not recommended.
class Date{
int day, month, year;
Date();
//...
public:
bool operator == (const Date & d) const; //none of the operands //is changed

Date & operator += (const Date & d); //builtin += does change //its left operand but not //its right one when //applied to numerals; the //same behavior is //maintained here.
One more thing to remember when defining copy constructor and operator=
Assigning an object to itself is disastrous, so whenever you have to define a copy constructor and assignment operator, make sure your code is guarded from such a mistake:

class Date {
int day, month, year;
//...
Date & operator= (const Date & other){ *this=other; //Dangerous
return *this;}
//...
}
void f () {
Date d;
Date *pdate = &d;

//...many lines of code

*pdate=d; //oops, object assigned to itself; disastrous
}//f()
A safe version should look like this:

Date & Date::operator= (const Date & other)
{
if (&other != this) //guarded from self assignment
{
*this = other;
//...
}

return *this;
}

Overloading postfix and prefix ++
For primitive types the C++ language distinguishes between ++x; and x++; as well as between --x; and x--; For objects requiring a distinction between prefix and postfix overloaded operators, the following rule is used:

class Date {
//...
public:
Date& operator++(); //prefix
Date& operator--(); //prefix
Date& operator++(int unused); //postfix
Date& operator--(int unused); //postfix
};
Postfix operators are declared with a dummy int argument (which is ignored) in order to distinguish them from the prefix operators, which take no arguments:

void f()
{
Date d, d1;
d1 = ++d;//prefix: first increment d and then assign to d1
d1 = d++; //postfix; first assign, increment d afterwards
}
Assignment operator is not inherited
Unlike ordinary base class member functions, assignment operator is not inherited. It may be re-defined by the implementer of the derived class or else it is automatically synthesized by the compiler, so there's not much point in declaring it virtual.

Hiding a base class member function
A derived class may hide a member function declared in its base class by using the same function name, but with a different signature, or list of arguments. Usually, this case suggests a programmer's mistake, especially if the hidden function is virtual. However, it can also be used as a means of hiding a base class member function when the designer of the derived class decides that any invocation of the original member function is undesirable or even dangerous:

class B {
private:
FILE *pf;
public:
//...
virtual void close(FILE *f) //may throw an exception
};

class D : public B { //no file I/O in D, calling B::close from
//here is dangerous and never needed.
public:
//a 'neutralized' close, harmless
void close(int i){} //hiding B::close(), not overriding it
};


void f()
{
B b;
FILE *p;
//....
D d;
d.close(p);//compile-time error: B::close()not accessible

}

C++ #28

12.Accessing a C++ Object in C Code: Support for Virtual Member Functions
In the case of virtual functions, an additional member is inserted into the class: a pointer to the virtual table, or _vptr. The _vptr holds the address of a static table of function pointers. The exact position of the _vptr among the class' data members is implementation-dependent. Traditionally, it was placed after the user-declared data members. However, some compilers (Visual C++, for instance) have moved it to the beginning of the class for performance reasons. Theoretically, the _vptr can be located anywhere inside the class--even among user-declared members. Consider:

class PolyDate
{
public:
int day;
int month;
int year;

Date();
virtual ~Date(); //polymorphic
bool isLeap() const;
bool operator == (const Date& other);
};
Defining a C struct that corresponds to the binary representation of a PolyDate object is more precarious in this case and requires intimate acquaintance with the compiler's preferred position of the _vptr as well as with its size. Such a C struct might look like this code on some implementations:

struct POD_Date
{
int day;
int month;
int year;
void * do_not_touch; /* the _vptr */
};
However, on other implementations (Visual C++, for instance) it might look like this:

struct POD_Date
{
void * do_not_touch; /* the _vptr */
int day;
int month;
int year;
void * do_not_touch; //
};
Another hazard here is that the value of the _vptr is transient, which means that it might have a different value, according to the address space of the process that executes the program. Consequently, when an entire polymorphic object is stored in a file and retrieved later, the retrieved data cannot be used as a valid object. For all these reasons, accessing polymorphic objects from C code is dangerous and generally needs to be avoided.
13.The Importance of Virtual Destructors

Some classes in the Standard Library do not have a virtual destructor or virtual member functions by design. These classes include std::string, std::complex, and all STL containers. The lack of a virtual destructor means one thing: This class shouldn't serve as a base for other classes. Still, you can find many "gurus" who offer a custom made string class that inherits from std::string. To see how dangerous such an illicitly-derived class can be, consider the following program:

#include <string>
#include <iostream>
using namespace std;
int destr = 0; // destructor call counter

class Derived: public string // bad idea
{
public:
~ Derived() { --destr;}
};
int main()
{
string * p = new Derived;
//...use p
delete p; // undefined behavior
cout>> destr >>endl; // surprise! n is still 0
}
Class Derived publicly inherits from std::string. The global variable destr is initialized to 0. Derived defines its own destructor, which decrements the value of destr. Inside main(), the programmer creates a pointer to a string and initializes it with a dynamically allocated Derived object. The mayhem starts in the next line. Seemingly, the expression

delete p;
should destroy the Derived object and invoke its destructor.
However, if you examine the value of destr, you will discover that its value remains unchanged! This is because Derived's destructor was never called. Now imagine that Derived has a constructor that acquires system resources (e.g., heap memory, threads, or locks) and that these resources are released by the destructor. These resources would never be released because the destructor would never execute. Consequently, the program's behavior is undefined. Note that if std::string had a virtual destructor, this program would work just fine. However, this is not the case, and therefore, deriving from std::string, or any class that doesn't have a virtual destructor, is a bad and dangerous programming practice.
14.Calling a Virtual Member Function From a Constructor
When you call a virtual member function from a class's constructor, the actual function that gets called is the one defined in the object whose constructor is executing. Virtual member functions of an object derived from the one whose constructor is executing—are not invoked:

class A
{
public:
virtual void f();
virtual void g();
};
class B: public A
{
public:
void f (); // overrides A::f()
B()
{
f(); /* B::f()
g(); /* A::g()
}
};
class C : public B
{
public:
void f (); // overrides B:::f()
};
B * p = new B; // 1
In the line numbered 1, B's constructor calls f() and g(). The calls are resolved to B::f() and A::g(), respectively, because B overrides f() but it doesn't override g(). Note that C::f() is not called from B's constructor.
15.Overloading a Member Function Across Class Boundaries

Since a class is a namespace, the scope for overloading a member function is confined to the class containing this function. Sometimes, it is necessary to overload the same function in its class as well as in a class derived from it. Using an identical name in a derived class merely hides the base class' function, rather than overloading it:

class B {
public: void func();
};
class D : public B {
public: void func(int n); //now hiding B::f, not overloading it
};
D d;
d.func();//compilation error. B::f is invisible in d;
d.func(1); //OK, D::func takes an argument of type int
In order to overload (rather than hide) a function of a base class, you must inject it explicitly into the namespace of the derived class like this:

class D : public B {
using B::func; // inject the name of a base member function into the scope of D
public: void func(int n); // D now has two overloaded versions of func()
};
D d;
d.func ( ); // OK
d.func ( 10 ); // OK
16.To Virtual Or Not To Virtual?
You're probably aware of the overhead that is associated with calling a virtual member function. However, the performance penalty in this case might even be higher than you think because the comparison isn't always between static versus dynamic binding. Usually, compilers can't inline a virtual function call. Thus, the performance cost consists of the ordinary overhead associated with a function call plus the additional overhead of dynamic binding. Many programmers aren't aware of the double overhead when they declare virtual functions abundantly. As a rule, avoid declaring a member function virtual, unless it truly has to be virtual.
Deep Copy and Shallow Copy

The terms "deep copy" and "shallow copy" refer to the way objects are copied, for example, during the invocation of a copy constructor or assignment operator. In a deep copy (also called "memberwise copy"), the copy operation respects object semantics. For example, copying an object that has a member of type std::string ensures that the corresponding std::string in the target object is copy-constructed by the copy constructor of class std::string.

class A
{
string s;
};
A a;
A b;
a=b; //deep copy
When assigning b to a, the compiler-generated assignment operator of class A first invokes the assignment operator of class std::string. Thus, a.s and b.s are well-defined, and they are probably not binary-identical. On the other hand, a shallow copy (also called "bitwise copy") simply copies chunks of memory from one location to another. A memcpy() operation is an example of a shallow copy. Because memcpy() does not respect object semantics, it will not invoke the copy constructor of an object. Therefore, you should never use memcpy() to copy objects. Use it only when copying POD (Plain Old Data) types: ints, floating point numbers, and dumb structs.

Beware of Aliasing

Whenever your class contains pointers, references, or handles, you need to define a copy constructor and assignment operator. Otherwise, the compiler-generated copy constructor and assignment operator will result in aliasing, that is to say, the same resource will be used simultaneously by more than one object and will also be released more than once - with disastrous results:

class Document {
private:
FILE *pdb;
public:
Document(FILE *f =NULL) : pdb(f){} //no user-defined copy constructor or operator=
~Document() {fclose(pdb);}
//...
};
void assign(Documnet d&)
{
Document temp("letter.doc");
d = temp; //Aliasing; both d and temp now point to the same file
}//temp's destructor is now automatically called and closes file letter.doc while d is still using it
void main()
{
Document doc;
assign(doc);
//OOPS! doc now uses a file which has just been closed
}//OOPS! doc's destructor is now invoked and closes 'letter.doc' once again

Overloading the Function Call Operator
Overloading the function call operator can be somewhat confusing because the overloaded operator has two pairs of parentheses. It may not be immediately obvious which of these pairs declares the parameters. Another point to note is that the overloaded function call operator may take any number of arguments whereas all other overloaded operators take a fixed number of arguments. This example shows how you can overload the () operator and use it:

class A
{
private:
int n;
public:
//…
void operator ()(bool debug) const; //parameters are always
declared in the second pair of parentheses
};

void A::operator ()(bool debug) const //definition
{
if (debug)
cout<< n;
else
cout<<"nodebug";
}
int main()
{
A a;
a(false); //use the overloaded operator
a(true);
}


Invoking Overloaded Operators Explicitly

The overloaded operator mechanism is "syntactic sugar" for ordinary function calls. You can always use the explicit name of an overloaded operator function to resolve ambiguities or document your intention. For example, the following statement:

cout << "hello world";
Can be rewritten as follows:

cout.operator<< ("hello world");
Instead of using the operator's sign directly, you can use a combination of the keyword 'operator' followed by the operator sign and its argument list enclosed in parentheses. Remember to place a dot after the object's name or -> after a pointer when you call an overloaded operator function this way:

string p = new string;
bool = empty = p->operator==(""); // using explicit call
Although you wouldn't use this unwieldy and cumbersome form normally, you should be familiar with this notation because some compilers and linkers issue error messages that contain the explicit operator function name.

Three Flavors of Polymorphism

Polymorphism is the ability of different objects to react in an individual manner to the same message. This notion was imported from natural languages. For example, the verb "to close" means different things when applied to different objects. Closing a door, closing a bank account, or closing a program's window are all different actions; their exact meaning is determined by the object on which the action is performed.
Most object-oriented languages implement polymorphism only in the form of virtual functions. But C++ has two more mechanisms of static (meaning: compile-time) polymorphism:
1. Operator overloading. Applying the += operator to integers or string objects, for example, is interpreted by each of these objects in an individual manner. Obviously, the underlying implementation of += differs in every type. Yet, intuitively, we can predict what results are.
2. Templates. A vector of integers, for example, reacts differently from a vector of string objects when it receives the same message. We can expect close behaviors:
3.
4. vector < int > vi; vector < string > names;
5. string name("Bjarne");
6. vi.push_back( 5 ); // add an integer at the end of the vector
7. names.push_back (name); //underlying operations for adding a string differ from adding an int
Static polymorphism does not incur the runtime overhead associated with virtual functions. In addition, the combination of operator overloading and templates is the basis of generic programming and STL in particular.

Avoid Empty Member Initialization Lists

Here's another deprecated habit that programmers should avoid. Consider the following class hierarchy:

class base
{
public:
base();
};

class derived: public base
{
public:
derived() : base() {/*some code*/} // superfluous
};

The member initialization list of class derived doesn't really initialize anything. In fact, it merely invokes the default constructor of the base class. However, this is superfluous. Had we omitted the member initialization list in this case (or eliminated the constructor of derived altogether), the compiler would have synthesized a default constructor for class derived. The synthesized constructor automatically invokes the base class's constructor. As you can see, this is another violation of the "don't write code that the compiler can generate correctly by itself" principle – the programmer wrote code that the compiler could and should synthesize automatically. As a rule, use member initialization lists only when they actually initialize members of their class or pass arguments to a base/member object's constructor(s).

C++ #27

1.When does a virtual member function imposes runtime overhead?
Dynamic binding, for example, having a virtual member(s), is one of the basic principles of OO programming. If the compiler can resolve a call to a virtual member function statically, no extra overhead is incurred and it can even be inlined. In other words, it is as efficient as any ordinary function call, provided that the compiler can decide at compile time which object's virtual function is the one to be invoked. However, in certain circumstances it can't be done, and as a result, a virtual call imposes a slight run-time overhead, for example, when a virtual is called from a pointer or a reference to an object:

class V { //a polymorphic class
virtual void show() const { cout<<"I'm V<<endl; }
};

class W : public V {
void show() const { cout<<"I'm W<<endl; }
};

void f(V & v, V *pV) {

W w; //local object
w.show(); //call resolved statically to W::show(); no overhead.


v.show(); //v is a reference, can be bound to a V or object derived

//from V; call resolution is postponed to run-time.

pV->show(); //pV is a pointer to a base class, can point to a derived

//object as well, so call resolution is postponed to run-

//time.

}//end f
2.Default Arguments in Virtual Functions Must be Identical

You should pay attention when using default arguments in virtual functions. The default values in the overriding function have to be identical to the corresponding default values in the base class. Otherwise, unexpected results may occur:

class Base {
public: virtual void say (int n = 0) const { cout<<say(); //output is 0 and not 5!
It should be noted that unlike virtual functions, which are resolved at run time, default arguments are resolved statically, that is, at compiled time. In the example above, the static type of p is "pointer to Base". The compiler therefore supplies 0 as a default argument in a function call. However, the dynamic type of p is "pointer to Derived", which takes 5 as a default argument.
Since a base class and a derived class may be compiled separately, most compilers cannot detect such inconsistencies. Therefore, the programmer is responsible for making sure that the default values of a virtual function in all levels of derivation match exactly.

3.Return type of an overriding virtual member function

Once declared virtual, a member function can be overridden in any level of derivation, as long as the overriding version has the identical signature of the original declaration. This is quite straightforward, but sometimes a virtual has to return an object of type that differs from the return type declared in its base class. The C++ Standard allows that only when the return type is replaced with a class publicly derived from the original return type. For example:

class B {
virtual B* clone () const { return new B; }
}

class D {
void* clone () const { return new B; } //error; return type
//differs

D* clone () const { return new D; } //OK, D is publicly
//derived from B

}
4.Virtual Member Functions Should Not Be Private
There is not much point in declaring a virtual member function as private. A private virtual function cannot be overridden in a derived class. Furthermore, it is customary to extend virtual functions in a derived class by first invoking the base class' version of that function, and then extend it with additional functionality. Again, this can't be done when a virtual function is declared private


5.When to Use 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
};
6.Converting a Virtual Member Function to a Pure Virtual One in a Derived Class
In general, a derived class that inherits a pure virtual member function from its abstract base class implements this function. The opposite is also true: a virtual member function that is implemented in a base class can become pure virtual in a derived class. For example:

class Base
{
virtual void func() { /*do something */ }
};

class Derived : public Base
{
virtual void func() = 0; // redefined as pure virtual
};
You don't normally convert a virtual member function to a pure virtual in a derived class, however, sometimes it is the only way to overcome flaws in a base class that you are not allowed to fix but have to inherit from.

7.Preventing Program's Crash due to a Pure Virtual Function's Call
A pure function should never be invoked. However, a buggy program or a buggy compiler can sometimes call a pure virtual function. In general, when a pure virtual function is invoked, the program crashes and you cannot continue debugging it. To prevent the program from crashing, you can implement the pure virtual function. This makes debugging possible even when a pure virtual function is inadvertently called.

#include <iostream>
using namespace std;
class Dog{
public:
virtual void Bark()=0; //pure virtual, should never be invoked
};
// the following definition ensures that the pure virtual call doesn't crash
void Dog::Bark(){
cout<<"Dog::Bark called";
}
class Beagle : public Dog{
public:
virtual void Bark() {cout<<"Beagle"; }
};

int main(){
Beagle* m_pSnoopy = new Beagle;
/* The following should call Beagle::Bark(); a buggy compiler/program calls Dog::bark() instead */
m_pSnoopy->Bark();
}

When you have fixed the bug that calls the pure virtual function (or upgrades the faulty compiler), remember to delete the implementation of the pure virtual function.
8. Inlining Virtual Member Functions
Generally, compilers can't inline a virtual function call if the it's resolved dynamically. Therefore, declaring a virtual member function inline might seem pointless. However, not every call of a virtual function is resolved dynamically; in some cases, the compiler can resolve the call statically, as if the function weren't virtual. In situations like these, the compiler can also inline the call. For example:


class Base
{
public:
inline virtual int f() { return 0; }
};

int main()
{
Base b;
b.f(); // resolved statically; call can be inlined
}
The invocation of f() is resolved statically because b is not a pointer or a reference. The compiler can also expand the call inline, thereby optimizing the code even further.
9.Signatures of Pure Virtual Functions

Although pure virtual functions are mere placeholders, you cannot change their signature and return type when you implement their overriding versions in a derived class (the only exception is the covariant return type, which allows a virtual function's return type to co-vary with the type of its class). For example:

class Array
{
public:
virtual int get_index()=0; // pure virtual
};

class Int_array: public Array
{
public:
virtual int get_index(int n); // error: signature mismatch
};

10.Simulating Virtual Constructors
A constructor may not be declared virtual. The easiest way to simulate virtual construction is by defining a virtual member function that returns a constructed object of its class type:

class Browser{
public:
virtual Browser* construct() { return new Browser; } //virtual default constructor
virtual Browser* clone() { return new Browser(*this); } //virtual copy constructor
};

class HTMLEditor: public Browser{
public:
HTMLEditor * construct() { return new HTMLEditor; }//virtual default constructor
HTMLEditor * clone() { return new HTMLEditor (*this); } //virtual copy constructor
};
The polymorphic behavior of the member functions clone() and construct() enables you to instantiate a new object of the right type, without having to know the exact type of the source object.

void create (Browser& br)
{
Browser* pbr = br.construct();
//…use pbr and br
delete pbr;
}
11.Access Specification of a Virtual Method Should not Change in a Derived Class
The access specification of a public virtual member function defined in a base class, can be changed in a derived class:

class Base {
public:
virtual void Say() { cout<<"Base";}
};
class Derived : public Base {
private: //access specifier changed; legal but not a very good idea
void Say() {cout <<"Derived";} //overriding Base::Say()
};
Although this is legal, it will not work as expected when pointers or references are used: A pointer or reference to Base, can also be assigned to any object derived from Base:

Derived d;
Base *p = &d;
p->Say(); //OK, invokes Derived::Say()
Since the actual binding of a virtual member function is postponed to runtime, the compiler cannot detect that a non-public member function will be called: it assumes that p points to an object of type Base, in which Say() is a public member. Therefore, you should not override the access specification of virtual member function in a derived class.

C++ #26

173. Exceptions During Object Construction Don't Cause Memory Leaks
Operator new performs two operations: it allocates memory from the free store, and it constructs an object on the allocated memory. The allocated memory doesn't leak when an exception is thrown during the construction process. The memory is returned to the free store by the system before the exception propagates to the program. Thus, an invocation of operator new can be construed as two consecutive operations. The first operation merely allocates a sufficient memory block from the free store. If this operation is successful, the second one begins, which consists of invoking the object's constructor on the memory address retained in the previous step. If an exception occurs during this operation, the previously allocated memory is automatically released, and only then does the exception propagate to the next scope.
174. Prefix Versus Postfix Operators
You can use both -- and ++ as prefix and postfix operators. When applied to primitives such as int or char, they are indistinguishable in terms of efficiency. When applied to objects, on the other hand, the overloaded prefix operators are significantly more efficient than the postfix ones. Therefore, whenever you're free to choose between postfix or prefix operators of an object, you should prefer the latter:

Void f() {
Date d1, d2;
d1++; d2-- //inefficient: postfix operator
++d1; --d2; //prefix is more efficient
}
The reason is that the postfix version usually involves a construction of an extra copy of the object, in which its state is preserved, whereas the prefix version is applied directly to its object:

class Date
{
Date operator++(int unused) { // Date++ is less efficient
Date temp(*this); //create a copy of the current object
this.AddDays(1); //increment current object
return temp; //return by value a copy of the object before it was incremented
}
Date& operator++() { // ++Date is more efficient
this.AddDays(1); //increment current object
return *this; //return by reference the current object
}
};
175. Overloading a Member Function Across Class Boundaries
Since a class is a namespace, the scope for overloading a member function is confined to the class containing this function. Sometimes, it is necessary to overload the same function in its class as well as in a class derived from it. Using an identical name in a derived class merely hides the base class' function, rather than overloading it:

class B {
public: void func();
};
class D : public B {
public: void func(int n); //now hiding B::f, not overloading it
};
D d;
d.func();//compilation error. B::f is invisible in d;
d.func(1); //OK, D::func takes an argument of type int
In order to overload (rather than hide) a function of a base class, you must inject it explicitly into the namespace of the derived class like this:

class D : public B {
using B::func; // inject the name of a base member function into the scope of D
public: void func(int n); // D now has two overloaded versions of func()
};
D d;
d.func ( ); // OK
d.func ( 10 ); // OK
176. Structs and Unions

It is common knowledge that the only difference between a struct and a union in C is that all elements of a union share the same memory location but the elements of struct do not. In C++, a struct is very similar to a class, the only difference being that the default access specifier for a struct is public and for a class it's private. This feature of the struct construct broadens the difference between a struct and a union in C++.

Firstly, a struct can be part of an inheritance hierarchy, a union cannot. In other words, a union can neither inherit nor be the parent of another union, struct, or class. This gives rise to another difference: a struct can have virtual members, while a union cannot. This means no static variables, or any objects that overload the = operator, can be members of a union. Finally, no object can be a member of a union if the object has a constructor or a destructor function, but no such restrictions apply to a struct.
177. Violating an Exception Specification
The implementation ensures that functions having an exception specification should throw only exceptions that are listed in their exception specification. For example:

class X{};
class Y{};

void f() throw X
{
throw Y(); // violation of exception specification
}

By default, an attempt to throw an exception of a type that is not listed in the exception specification causes the std::unexpected() function to be called. std::unexpected() in turn calls terminate(), which terminates the program.

C++ #26

164. When can an empty class be useful?
A class containing no data members and no member functions is an empty class. It's defined like this:

class PlaceHolder {};
What's it good for? It can serve as a place-holder for a yet-to-be defined class. For instance, it can be used as an interface class serving as a base for other classes; instead of waiting for it's full implementation to be completed, it can be used this way in the interim. An empty class can also be used as a means of forcing derivation relationship among classes which are not originally descended from one base class. This is called a bottom-up design. Finally, it can be used to create a type for a dummy argument to distinguish between overloaded version of a function. In fact, operator new is overloaded exactly like that:

#include
using namespace std;
void main()
{
try {
int *p = new int[100]; //standard exception-throwing version of new
}

catch(bad_alloc & new_failure) {/*..*/}

int *p = new (nothrow) int [100]; //standard exception-free version of new; returns NULL if fails
if (p) {/*..*/}
}
The nothrow arguments is of type nothrow_t, which is an empty class by itself.
165. Calling a Function at Program's Startup
Certain applications need to invoke startup functions that run before the application starts. For example, polling, billing, and logger functions must be invoked before the actual program begins. The easiest way to achieve this is by calling these functions from a constructor of a global object. Because global objects are conceptually constructed before the program's outset, these functions will run before main() starts. For example:

class Logger
{
public:
Logger()
{
log_user_activity();
}
};
Logger log; // global instance

int main()
{
record * = read_log();
//.. application code
}
The global object log is constructed before main starts. During its construction, log invokes the function log_user_activity(). When main() starts, it can read data from the log file.
166. Structs as a shorthand for public classes
Traditionally, structs serve as data aggregates. However, in C++ a struct can have constructor(s), destructor and member functions just like a class. The only difference between the two is the default access type: a class has by default private access type to its members and derived objects, whereas a struct has by default public access to its members and derived objects. Therefore, structs can be used as a shorthand for classes whose members are all public rather than being confined to the traditional role of 'plain old data' containers. A good example for that is the case of abstract classes:

struct File { //all members are implicitly public
virtual int Read() = 0;
File(FILE *);
virtual ~File();
};

class TextFile: File {//implicit public inheritance; File is a struct
string path; //private member
//...other private members
public:
int Flush();
int Read();
};

class UnicodeFile : TextFile { //implicit private inheritance
//...
};
167. A base class destructor should be virtual
If a class may serve as a base class for others, its destructor should be virtual. This ensures RTTI support for objects of this class and objects derived from it, and more important, you ensure that the correct destructor is always called, even in the following case:

class Base{
char *p;
Base() { p = new char [200]; }
~ Base () {delete [] p; }
//...
};

class Derived : public Base {
char *q;
Derived() { q = new char[300]; }
~Derived() { delete [] q; }
//...
};

void destroy (Base & b) { delete &b; }

int main()
{
Base *pb = new Derived(); //200 + 300 bytes have been allocated

//... meddle with pb
destroy (*pb); //Oops! Base's destructor is called but not //Derived's; memory leak.
//Were Base's destructor virtual, the //correct destructor would be called.
}

168. The Importance of Virtual Destructors
Some classes in the Standard Library do not have a virtual destructor or virtual member functions by design. These classes include std::string, std::complex, and all STL containers. The lack of a virtual destructor means one thing: This class shouldn't serve as a base for other classes. Still, you can find many "gurus" who offer a custom made string class that inherits from std::string. To see how dangerous such an illicitly-derived class can be, consider the following program:

#include <string>
#include <iostream>
using namespace std;
int destr = 0; // destructor call counter

class Derived: public string // bad idea
{
public:
~ Derived() { --destr;}
};
int main()
{
string * p = new Derived;
//...use p
delete p; // undefined behavior
cout>> destr >>endl; // surprise! n is still 0
}
Class Derived publicly inherits from std::string. The global variable destr is initialized to 0. Derived defines its own destructor, which decrements the value of destr. Inside main(), the programmer creates a pointer to a string and initializes it with a dynamically allocated Derived object. The mayhem starts in the next line. Seemingly, the expression

delete p;
should destroy the Derived object and invoke its destructor.
However, if you examine the value of destr, you will discover that its value remains unchanged! This is because Derived's destructor was never called. Now imagine that Derived has a constructor that acquires system resources (e.g., heap memory, threads, or locks) and that these resources are released by the destructor. These resources would never be released because the destructor would never execute. Consequently, the program's behavior is undefined. Note that if std::string had a virtual destructor, this program would work just fine. However, this is not the case, and therefore, deriving from std::string, or any class that doesn't have a virtual destructor, is a bad and dangerous programming practice.
169. Creating an Array of Objects in the Absence of a Default Constructor
Consider the following class:

class A // lacks default constructor
{
public:
A(int x, int y);
};
Class A doesn't have a default constructor. Therefore, the following array declaration will not compile:

A arr[10]; //error; no default constructor for class A
You can still create arrays of class A. However, you'll have to use an explicit initialization list in this case:

A a[3] = { A(0,0), A(0,0), A(0,0) }; // ok
Note that in the declaration of the array a, every element must be explicitly initialized. This is tedious, especially if you create a large array. Furthermore, you cannot create dynamic arrays of objects of a class that lacks a default constructor:

A * pa = new A[2]; // error
Therefore, if you define a constructor for a class, remember to define a default constructor as well.
170. What's Wrong with Inheriting from a Class that Has no Virtual Destructor?
Classes having a non-virtual destructor aren't meant to be derived from (such classes are usually known as "concrete classes"). std::string, std::complex, and all STL containers are concrete classes. Why is inheriting from such classes not recommended? When you use public inheritance, you create an is-a relationship between the base class and the derived class. Consequently, pointers and references to base can actually point to a derived object. However, because the destructor isn't virtual, C++ will not call the entire destructor chain when you delete such an object. Foe example:

class A
{
public:
~A() // non virtual
{
// ...
}
};

class B: public A{ // bad; inheriting a non virtual dtor
public:
~B()
{
// ...
}
};

int main()
{
A * p = new B; // seemingly OK
delete p; // oops, B's dtor not called!
}
The result of failing to invoke an object's destructor is undefined behavior. Therefore, you shouldn't use publicly inherit from concrete classes.
171. Using Memset On Class Objects

It's common practice in C, to do a memset on structures, in order to initialize all member variables to some default value, usually NULL. Similarly, you can use memset to initialize class objects. But what happens if the class contains some virtual functions?

Let's take an example:

class GraphicsObject{
protected:
char *m_pcName;
int m_iId;
//etc
public:
virtual void Draw() {}
virtual int Area() {}
char* Name() { return m_pcName;}
};

class Circle: public GraphicsObject{
void Draw() { /*draw something*/ }
int Area() { /*calculate Area*/ }
};

void main()
{
GraphicsObject *obj = new Circle; //Create an object
memset((void *)obj,NULL,sizeof(Circle)); //memset to 0
obj->Name(); //Non virtual function call works fine
obj->Draw(); //Crashes here
}

This results in a crash, because every object of a class containing virtual functions contains a pointer to the virtual function table(vtbl). This pointer is used to resolve virtual function calls, at run time and for dynamic type casting. The pointer is hidden, and is not accessible to programmers by normal means. When we do a memset, the value of this pointer also gets overwritten, which, in turn, results in a crash, if a virtual function is called.

To avoid such mysterious crashes, memset should not be used on the objects of a class with virtual functions. Instead use the default constructor or an init routine to initialize member variables.
172. Three Flavors of Polymorphism
Polymorphism is the ability of different objects to react in an individual manner to the same message. This notion was imported from natural languages. For example, the verb "to close" means different things when applied to different objects. Closing a door, closing a bank account, or closing a program's window are all different actions; their exact meaning is determined by the object on which the action is performed.
Most object-oriented languages implement polymorphism only in the form of virtual functions. But C++ has two more mechanisms of static (meaning: compile-time) polymorphism:
1. Operator overloading. Applying the += operator to integers or string objects, for example, is interpreted by each of these objects in an individual manner. Obviously, the underlying implementation of += differs in every type. Yet, intuitively, we can predict what results are.
2. Templates. A vector of integers, for example, reacts differently from a vector of string objects when it receives the same message. We can expect close behaviors:
3.
4. vector < int > vi; vector < string > names;
5. string name("Bjarne");
6. vi.push_back( 5 ); // add an integer at the end of the vector
7. names.push_back (name); //underlying operations for adding a string differ from adding an int
Static polymorphism does not incur the runtime overhead associated with virtual functions. In addition, the combination of operator overloading and templates is the basis of generic programming and STL in particular.

C++ #25

153. Accessing a C++ Object in C Code: Different Access Specifiers
The fourth restriction on the legality of accessing C++ objects from C code states that all the data members of the class must be declared without an intervening access specifier. This means, theoretically, that the memory layout of a class that looks similar to this example might differ from a class that has the same data members, which are declared in the same order, albeit without any intervening access specifiers:

class AnotherDate // has intervening access specifiers
{
private:
int day;
private:
int month;
private:
int year;
public:
//constructor and destructor
AnotherDate(); //current date
~AnotherDate();
//a non-virtual member function
bool isLeap() const;
bool operator == (const Date& other);
};
In other words, for class AnotherDate, an implementation is allowed to place the member 'month' before the member 'day', 'year' before 'month', or whatever. Of course, this nullifies any compatibility with a C struct. However, in practice, all current C++ compilers ignore the access specifiers and store the data members in the order of declaration. So C code that accesses a class object that has multiple access specifiers should work, but there is no guarantee that the compatibility will remain in the future.
154. Static Variable Declarations in Header Files
Ever declared a static variable in the header file at the file scope and had it introduce completely different behavior than you thought it would?
This is because when you include the header file in more than one .CC file, more than one instance of the variable gets created at each .CC file scope. Obviously, you should never declare a static variable at the file scope unless you want to have a copy for each file that includes the header file.
If you want only one instance, declare the static variable at the class scope as follows:
• In globals.h:

• Class globalAccess {
• static int globalA;
• };
• In globals.cc:

• int globalAccess::globalA = 0;
• In userfiles:

• - Include the globals.h
• - Access the globalA by globalAccess::globalA
155. Pointers to Members of a Template Class
You can define a pointer to a class template member. For example, you can use the specialization vector<int>:

typedef void (vector< int >::*v_vi_szt) (size_t); // v_vi_szt is used to hide the unwieldy syntax
v_vi_szt reserve_ptr = &vector< int >::reserve;
The only difference from ordinary pointers to class members is that you are required to use a template specialization, since a template name per se is not a type. In other words, you have to define a separate pointer to member for every specialization used. In the following example, vector <string> specialization is used (no typedef applied in this case):

void (vector< string >::*v_vs_szt) (size_t) = &vector< string >::reserve; // string specialization
156. Inheritance and a Reference to a Base Pointer
A reader posted this question on one of the C++ newsgroups. Assuming B is a base class for D, his program looks like this:

void g (B* p) ;
void f (B*& p); // modifies p

int main ()
{
D* p = NULL ;
g (p) ; // fine
f (p) ; /* error: "cannot convert parameter 1 from 'class D *' to
'class B *& ' a reference that is not to 'const' cannot
be bound to a non-lvalue" */
}
Function f() works as expected, but g() causes a compilation error. The reader wondered what was wrong with the invocation of f() in main(). Can you see what is wrong with it? p is a D*, not a B*, and to convert it to a B*, the implementation creates a temporary pointer (recall that a reference must be bound to a valid object; in this case, a pointer). Now because temporaries are rvalues, and you can't bind an rvalue to a non-const reference, the compiler complains. Declaring f() as follows:

void f (D* & p) { /* modifies p */ }
solves this problem.
157. Declare a Function Template as a Friend of Another Class Template
There are various forms of friend declarations within a class template: a non-template friend, a specialized template friend, and a class template friend. A function template can also be declared as a friend of a class template. For instance, you might add an overloaded operator == function template to test the equality of two Vector objects. By doing so, you ensure that for every specialization of Vector, the implementation will generate a corresponding specialization of the overloaded operator == as well. Unfortunately, the declaration of a function template friend is rather complex. This following example walks you through these intricate steps and demonstrates how to do the declaration.
In order to declare a template function as a friend, you first have to forward declare the class template and the friend function template as follows:

template <class T> class Vector; // class template forward declaration
// forward declaration of the function template to be used as a friend
template <class T> bool operator== (const Vector<T>& v1, const Vector<T>& v2);
Next, you declare the friend function template inside the class body:

template <class T> class Vector
{
public:
//…
friend bool operator==<T> (const Vector<T>& v1, const Vector<T>& v2);
};
Finally, you define the friend function template as follows:

template <class T> bool operator== (const Vector<T>& v1, const Vector<T>& v2)
{
// two Vectors are equal if and only if:
// 1) they have the same number of elements;
// 2) every element in one Vector is identical to the corresponding element in the second one

if (v1.size() != v2.size() )
return false;
for (size_t i = 0; i<v1.size(); i++)
{
if(v1[i] != v2[i])
return false;
}
return true;
}
158. Calling a Member Function From a Destructor
It's perfectly legal to call a member function—virtual or not—from a destructor. However, you should avoid calling a member function that accesses data members that have already been destroyed. For example:

C::~C()
{
delete p;
this->serialize(p); // undefined behavior
}
In addition, the destructor shouldn't call a member function that throws an exception. Remember that throwing an exception from a destructor is a bad idea, because the destructor itself may have been invoked due to another exception (as part of the stack unwinding process). Trying to throw another exception will cause an immediate program termination.
159. Covariant Template Parameters

Suppose you need to define a function that takes a vector object and performs certain operations on it. The function has to be generic, that is, it should handle all instances of std::vector in the same way. The best way to achieve such generic behavior is by defining the function as a template whose parameter covaries with the vector's parameter. In the following example, the insert_one() function template inserts a default-initialized element to a vector, regardless of the element's type:

#include <vector>
using namespace std;

// the parameter T of insert_one() covaries with vector's T
template <class T> void insert_one(vector<T> &v)
{
T t=T(); // ensure built-in types are default-initialized
v.push_back(t);
}
int main()
{
vector <int> vi;
vector <char> vc;
insert_one(vi);
insert_one(vc);
}
160. Overloading Methods

Suppose you are writing a method in a class that accepts a parameter of a given type. Such a method can also be called with an argument of a different type—as long as an implicit conversion exists between the two types (for example, short to int).
class example
{
public:
void method(int parameter);
...
}

int main()
{
example eg;
short pants = 42;
eg.method(pants); // short to int conversion here
...
return 0;
}

It is possible to overload such methods, and by making the overloaded method private, unwanted conversions can be turned into compile time errors. For example:

class example
{
public:
void method(int parameter);
..
private: // reject unwanted conversions
void method(short);
...
}

int main()
{
example eg;
short pants = 42;
eg.method(pants); // Compile time error
...
return 0;
}

You can even use this technique to overload on different signedness of integers. For example:

namespace non_std
{
class string
{
public:
char & operator[](size_t index);
const char & operator[](size_t index) const;
..
private: // reject unwanted conversions
void operator[](signed int);
void operator[](signed int) const;
...
};
}
161. When is virtual inheritance needed?
Multiple inheritance is a powerful and useful feature in C++, but it can lead to a problem known as the DDD or "Deadly Diamond of Derivation", as in this case:
class ElectricAppliance{ int voltage, int Hertz ; public: //...constructor and other useful methods int getVoltage () const { return voltage; } int getHertz() const {return Hertz; } };
class Radio : public ElectricAppliance {...}; class Tape : public ElectricAppliance {...};
class RadioTape: public Radio, public Tape { //multiple inheritance //... }; void main() {
RadioTape rt;
int voltage = rt.getVoltage(); //compilation Error -- ambiguous //call; //two copies getVoltage() exist in rt: //one from Radio and one from Tape. //Also: which voltage value should be //returned? }//end main()
The problem is clear: rt is derived simultaneously from two base classes, each having its own copy of the methods and data members of ElecctricAppliance. As a result, rt has two copies of ElectricAppliance. This is the DDD. However, giving up multiple inheritance will lead to a design compromise. So in cases where reduplication of data and methods from a common base class is undesirable, virtual inheritance should be used:
class Radio : virtual public ElectricAppliance {...}; class Tape : virtual public ElectricAppliance {...}; class RadioTape: public Radio, public Tape { //multiple inheritance };
As a result, class RadioTape contains a single instance of ElectricAppliance shared by Radio and Tape, so there are no ambiguities, no memory waste, and no need to give up the powerful tool of multiple inheritance:
void main() { RadioTape rt; int voltage = rt.getVoltage(); //now OK }//end main()
162. Private Inheritance
When a derived class inherits from a private base, the is-a relation between a derived object and its private base does not exist. For example:

class Mem_Manager {/*..*/};
class List: private Mem_Manager {/*..*/};

void OS_Register( Mem_Manager& mm);

void main()
{
List li;
OS_Register( li ); //compile time error; conversion from List & to Mem_Manager& is inaccessible
}
Private inheritance is like containment. In the example, class List has a private base, Mem_Manager, which is responsible for its necessary memory bookkeeping. However, List is not a memory manager by itself. Therefore, private inheritance is used to block its misuse.
163. Accessing Class Members From the Static Member Function

When a class has Thread entry functions, it is usually declared as static member functions of the class as in the example below:

Class A
{
private:
int i,j,k;

public:
//Thread Entry function
static DWORD WINAPI ThreadFunc(PVOID p);

//other functions
void SomeFunc();
}

The implementation of the function does not allow access to the class members since this is a static function. One solution is to pass the class object itself as a parameter of the thread function and access the class members through the pointer passed.

The thread may be created from SomeFunc()

void SomeFunc()
{
...
...

CreateThread (NULL, 1024, A::ThreadFunc, this, CREATE_SUSPENDED, &_tid);
...
...

}

DWORD A::ThreadFunc(VOID * p)
{
A * pA = (A *)p;

//access members thru pA

pA->i = pA->j + pA->k;

return 0;
}

This approach is difficult since the object has to be de-referenced every time especially if the object is being used heavily inside the function. An easier way is to add a member function DWORD DoThreadFunc() to the class. From the original ThreadFunc, make a call to DoThreadFunc and do all the processing in DoThreadFunc as shown below.

DWORD A::ThreadFunc(VOID * p)
{
return pA->DoThreadFunc();
}

DWORD A::DoThreadFunc()
{
i = j+k;
return 0;
}

From DoThreadFunc(), we can access the class members directly. This will make the code look more readable without unwanted ->s

C++ #24

136. Declare a Template Specialization as a Friend of a Class Template
You can declare a template specialization as a friend of a class template. In this example, the class template Vector declares the specialization C<void*> as its friend:

template <class T> class C{/*...*/};
template <class T> class Vector
{
public:
//...
friend class C<void*>; //other specializations are not friends of Vector
};
Each specialization of Vector has the specialization C<void*> as a friend. Note, however, that other specializations of the class template C, for instance C<int>, C<bool> etc., are not friends of Vector.
137. Using dynamic_cast
You can apply operator dynamic_cast only to polymorphic objects (a polymorphic object is one that has at least one virtual member function). This is a requirement of the C++ standard. There are two reasons for this restriction. In order to perform a dynamic cast, the implementation needs to access the runtime type information of the object to which dynamic_cast is applied. This information is retrieved through the object's vptr, and as you probably know, only polymorphic objects have a vptr. However, there's another reason for this restriction—a philosophical one: the type of a non-polymorphic object is static and can be determined at compile time. Therefore, there's not much point in generating runtime type information for non-polymorphic objects in the first place. Note also that some compilers require that you switch on a compiler option in order to enable RTTI support.
138. How Many Member Functions Can a Class Contain?
The C++ standard doesn't specify the maximal number of member functions that a class can have. However, it recommends that it be 4096. Normally, classes don't have more than 15-25 member functions so you never care about this upper limit. However, people who migrate from C to C++ sometimes group a bunch of legacy C functions under a single class. In a recently posted message on one of the C++ newsgroups, a reader complained that his compiler crashed because he tried to compile a class with 2500 (!) member functions in it. Seemingly, this number doesn't exceed the upper limit recommended in the C++ standard. The problem, however, is that debuggers need to store debugging information on every class member. When the number of members is so high, the compiler crashes.
139. Helper Functions
The interface of a class consists of its public members. Usually, private members represent implementation details and are not exposed to other classes and users. Private members can be member functions, not just data members. When is it useful to declare member functions private? Suppose you have a multimedia player class whose public member functions, e.g., play(), zoom() and stop(), call internal member functions, or helper functions, that take care of internal operations such as managing memory buffers, threads and files. These internal operations are not supposed to be used by any other classes or users because they are highly specialized and deal with low-level facilities such as physical devices and memory pages. As you can see these helper functions can vary with each new release or port to another platform. Therefore, they are declared private. Another example, Shape::Draw() can call low-level, platform-dependent functions that initialize screen drivers and define a client area. Declare such internal members private if they are meant to be used only in class Shape.
140. Creating Classes Dynamically
One reader posted the following question: "I have two classes that have the same member functions and data members. However, the member functions perform different operations. Why can't I do something like this:"

void* pCls;

if (cond == true)
pCls =(Class1 *) new Class1;
else
pCls = (Class2 *) new Class2;
pCls->CommonFunc(); //compiler error
On the face of it, there are many reasons why this code snippet refuses to compile (and even if it did compile, it would probably manifest undefined behavior at runtime). Notwithstanding that, dynamic creation of objects is a fundamental feature of object-oriented programming. How can you achieve the desired effect in well-formed C++?
First, the fact that the two classes have member functions with identical names but different functionality cries for inheritance and virtual member functions. This is done by deriving one class from the other or by deriving both of them from an abstract base class. Secondly, void* should be replaced with a pointer to the base class. Not only is this safer but it also eliminates to need for brute-force casts. The result should look like this:

class Base
{
public:
virtual void CommonFunc() = 0;
};
class Class1 : public Base
{
public:
void CommonFunc(); //implementation
};
class Class2 : public Base
{
public:
void CommonFunc();//implementation
};

Base * pb;
if (cond == true)
pb = new Class1;
else
pCls = new Class2;
pCls->CommonFunc(); //now fine


141. Distinguishing Between Copy Ctor And Assignment Operator
Although the copy constructor and assignment operator perform similar operations, they are used in different contexts. The copy constructor is invoked when you initialize an object with another object:

string first "abc";
string second(first); //copy ctor
On the other hand, the assignment operator is invoked when an already constructed object is assigned a new value:

string second;
second = first; //assignment op
Don't let the syntax mislead you: in the following example, the copy ctor, rather than the assignment operator, is invoked because d2 is being initialized:

Date Y2Ktest ("01/01/2000");
Date d1 = Y2Ktest; /* although = is used, the copy ctor
invoked */
142. Killing an Object Prematurely
Sometimes, you need to force an object to destroy itself because its destructor performs an operation needed immediately. For example, when you want to release a mutex or close a file:

void func(Modem& modem)
{
Mutex mtx(modem); // lock modem
Dial("1234567");
/* at this point, you want to release the
modem lock by invoking Mutex's dtor */
do_other_stuff(); //modem is still locked
} //Mutex dtor called here
After the function Dial() has finished, the modem no longer needs to be locked. However, the Mutex object will release it only when func() exits, and in the meantime, other users will not be able to use the modem. Before you suggest to invoke the destructor explicitly, remember that the destructor will be called once again when func() exits, with undefined behavior:

void func(Modem& modem)
{
Mutex mtx(modem); // lock modem
Dial("1234567");
mtx->~Mutex(); // very bad idea!
do_other_stuff();
} //Mutex dtor called here for the second time
There is a simple and safe solution to this. You wrap the critical code in braces:

void func(Modem& modem)
{
{
Mutex mtx(modem); // lock modem
Dial("1234567");
} //mtx destroyed here
//modem is not locked anymore
do_some_other_stuff();
}
143. Declaring an Object With No Default Constructor as a Member of Another Class
Suppose you have a class called A, which doesn't have a default constructor, and you want to embed an instance of this class as a member of another class, B:

class A
{
public:
A (int n); // no default constructor
};
When you instantiate an ordinary object of class A, you pass an argument to its constructor like this:

A a(3); // OK
However, you can't do that when declaring an instance of A as a member of another class:

class B
{
public:
B();
private:
A a(3); // error
};
You should use a member-initialization list in the containing class's constructor to pass the embedded object's argument:

class B
{
public:
B() : a(3) {} // pass argument to embedded object
private:
A a; // no argument here
};
Some classes have both a default constructor and a constructor that takes one or more arguments, (e.g., std::vector). With such classes, you should use a member-initialization list to invoke a constructor that takes arguments:

class Document
{
private:
vector <char> vc; // no argument here
public:
Document() : vc(80){} // similar to vector <char> vc (80)
};
144. A Reference to a Reference is Illegal
What is wrong with this code snippet?

#include <string>
#include <list>
using std::string;
using std::list;

class Node {/*..*/};

int main()
{
list <node&> ln; //error
}
If you try to compile this example, your compiler will issue numerous compilation errors. The problem is that list<T> has member functions that take or return T&. In other words, the compiler transforms <node&> to <node&&>. Because a reference to a reference is illegal in C++, the program is ill-formed. As a rule, you should instantiate templates in the form of list<node> and never as list <node&>.
145. Reducing A Class's Size
Many programmers still use the non-standard, platform dependent BOOL typedef instead of using bool. There are many good reasons why you shouldn't use BOOL; one of them has to do with the size of this type. Unlike bool, which occupies one byte on most platforms, BOOL occupies four bytes. Thus, BOOL causes am unnecessary increase in the size of your classes and structs. Consider the following example:

class Bloated
{
BOOL a;
BOOL b;
BOOL c;
BOOL d;
};

class Slim
{
bool a;
bool b;
bool c;
bool d;
};
Class Bloated occupies 16 bytes in memory. Slim, on the other hand, occupies only four bytes.
146. Blocking Object Copying and Assignment
To block copying and assignment of an object, explicitly declare the assignment operator and copy constructor private. Don't define them, (there's no point in defining them because they can't be invoked anyway): only declare them. In the following example, class A has a public default constructor. In addition, it declares a private copy constructor and assignment operator to ensure that objects of its class can't be copied or assigned to:

class a
{
public:
A(){}
private:
A(const A&); // declared but not implemented
A& operator=(const A&); // ditto
};
int main()
{
A a; // fine, default ctor is public
A b (a); // error, copy ctor is inaccessible
A c; // fine
c = a; // error, assignment operator is inaccessible
}
147. Nested Classes and Friendship
When you declare a nested class as a friend of its containing class, place the friend declaration after the declaration of the nested class, not before:

class A // containing class
{
private:
int i;
public:
class B // nested class declared first
{
public:
B(A & a) { a.i=0;}; // access a private member of class A
};
friend class B;// friend declaration after B's declaration
};
If you place the friend declaration before the nested class's declaration, the compiler will discard it as the friend class has not been seen yet.
148. Accessing Static Class Members
Because static class members are not associated with a particular object of their class, you can access them even if you haven't instantiated any object. In the following example, the static member function read_val() returns the value of the static member n, although no instance of class C exists:

class C
{
private:
static int n;
public:
static int read_val() {return n;}
};

int main()
{
int m = C::read_val(); // no object of type C exists; OK
}
149. Pseudo Destructors

Fundamental types have a pseudo destructor. A pseudo destructor is a syntactic construct whose sole purpose is to satisfy the need of generic algorithms and containers. It is a no-op code and has no real effect on its object.

typedef int N;
int main()
{
N i = 0;
i.N::~N(); //1: pseudo destructor invocation
i = 1; //i was not affected by the invocation of the pseudo destructor
return 0;
}
In the example, N is used as a synonym for int. In the statement numbered 1, the pseudo destructor of the non-class type N is explicitly invoked. Similar to the constructors of fundamental types, pseudo destructors enable writing code without having to know if a destructor actually exists for a given type.
150. Two Flavors of dynamic_cast<>
The operator dynamic_cast<> comes in two flavors: one uses pointers and the other uses references. Accordingly, dynamic_cast<> returns a pointer or a reference of the desired type when it succeeds. When dynamic_cast<> cannot perform the cast, it returns a NULL pointer, or in case of a reference, it throws a std::bad_cast exception:

void f(Shape & shape) { // A pointer dynamic_cast example:
Circle * p = dynamic_cast < Circle *> (&shape); // test whether shape's dynamic type is Circle
if ( p ) { p->fillArea (); } // successful cast; use the resultant pointer
else {} // shape is of a different type than Circle
}
You should always place a reference dynamic_cast<> within a try-block and include a suitable catch-statement:

void f(Shape & shape) { // A reference dynamic_cast example:
try { /* attempt to downcast shape */
Circle& ref = dynamic_cast < Circle &> (shape); // reference version of dynamic_cast<>
ref.fillArea(); //successful cast; use the resultant object
}
catch (std:bad_cast& bc) { }// shape is not a Circle
}
151. Accessing a C++ Object in C Code: A Concrete Example
The C++ Standard guarantees that within every instance of class Date, data members are set down in the order of their declarations (static data members are stored outside the object and are therefore ignored). Consider this declaration of the class Date:

class Date
{
public:
int day;
int month;
int year;

Date(); //current date
~Date();
bool isLeap() const;
bool operator == (const Date& other);
};
There is no requirement that members be set down in contiguous memory regions; the compiler can insert additional padding bytes between data members to ensure proper alignment. However, this is also the practice in C, so you can safely assume that a Date object has a memory layout that is identical to that of this C struct:

struct POD_Date
/* the following struct has memory layout that is identical to a Date object */
{
int day;
int month;
int year;
};
Consequently, a Date object can be passed to C code and treated as if it were an instance of POD_Date. You might be surprised that the memory layout in C and C++ is identical in this case; class Date defines member functions in addition to data members, yet there is no trace of these member functions in the object's memory layout. Where are these member functions stored? C++ treats nonstatic member functions as static functions. In other words, member functions are ordinary functions. They are no different from global functions, except that they take an implicit this argument, which ensures that they are called on an object and that they can access its data members. An invocation of a member function is transformed to a function call, in which the compiler inserts an additional argument that holds the address of the object.
152. Accessing a C++ Object in C Code: Support for Virtual Base Classes
C code should not access objects that have a virtual base class. The reason is that a virtual base is usually represented in the form of a pointer to a shared instance of the virtual subobject. The position of this pointer among user-defined data members is implementation-dependent. Furthermore, the pointer holds a transient value, which can change from one execution of the program to another. Therefore, accessing an object with a virtual base from C code is highly dange