Site Archive (Complete)
C++ Blog: Default constructors and assignment
C++
void main(void)

Calls, Returns and In-Between.

by Kevin Carlson
SELECTIVE IGNORANCE

Finding the Signal in the Noise

by Andrew Koenig
March 26, 2007

Default constructors and assignment

When should your class have a default constructor? Most C++ programmers know you need one if you want to create an array of your type, but are there other circumstances?

It occurred to me recently that you don't need a default constructor if objects of your class can never change their value once constructed. After all, if your objects are immutable, having a default constructor doesn't do you much good unless you happen to want an object that always has its default value.

The contrapositive of a true statement is also true--which means that a class that does need a default constructor must offer a way of changing the value of its objects. And if a class offers any way of changing its objects' value, it should probably have an assignment operator as well.

These two facts lead to the following somewhat surprising rule of thumb, which I have not seen before:

    If your class needs a default constructor, it should probably also have an assignment operator.

If you follow this rule, it means that whenever you can write

    T x = y;

you will be able to replace it by

    T x; x = y;

Indeed, the usefulness of this idiom suggests that the inverse of the rule may well make sense also, so that perhaps we should say

    Assignment operators and default constructors go together: If your class has one, it should have both.

Notice that it is possible for the assignment operator in this case to be generated by default. So, for example, the rule suggests that if you define a class such as

struct Point {
    Point(x0, y0): x(x0), y(y0) { }
    int x, y;
};

you should really define a default constructor as well, becuase otherwise the class will have a (compiler-generated) assignment operator but no default constructor.

I have not seen this rule of thumb discussed elsewhere; if you have seen it before now, I'd appreciate hearing about it.

Posted by Andrew Koenig at 12:13 PM  Permalink




 
INFO-LINK


Related Sites: DotNetJunkies, SD Expo, SqlJunkies