C++ interview

From Hawk Wiki
Revision as of 06:21, 15 December 2011 by Hall (Talk | contribs) (Created page with "==Explicit constructor== <pre> class Array { public: Array(size_t count); // etc. }; This seems innocent enough until you realize that you can do this: Array array = 12...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Explicit constructor

class Array
{
public:
    Array(size_t count);
    // etc.
};

This seems innocent enough until you realize that you can do this:

Array array = 123;

Well that’s ugly but hardly something to get excited about, or is it? This is known as an implicit conversion. The trouble is that it can occur in more insidious places. Consider the following function:

void UseArray(const Array& array);

Because the compiler will attempt to find an implicit conversion, the following code compiles just find:

UseArray(123);

Yikes! That’s terrible. First there is the problem of code clarity. What does this mean? Secondly, because the implicit conversion involves calling the Array constructor, presumably enough storage is being allocated for a new Array object, not to mention the memory reserved for 123 elements contained in the array. Surely this is not what the programmer intended!?

All of these subtleties can be avoided by making the Array constructor explicit:

class Array
{
public:
    explicit Array(size_t size);
    // etc.
};

Now a programmer needs to be explicit about her use of the Array constructor.

Array array(123);
UseArray(Array(123));

A thing of beauty.