Cast Constructor

A CastConstructor in CeePlusPlus is similar to a CopyConstructor, except that the type of the argument is different than the type being defined; i.e.

class Foo {
public:
Foo (const Bar &);
// more stuff
};

Like the CopyConstructor, the CastConstructor can be invoked either with "standard" constructor syntax:

Bar b;
Foo f(b);

or with "assignment" syntax

Bar b;
Foo f = b;

But wait...there's more. The CastConstructor also allows implicit casts to be performed, like this.

void snarf_the_foo (Foo &foo);
...
Bar b;
snarf_the_foo (b); // equivalent to snarf_the_foo (Foo(b));

which can surprise you. The explicit keyword can be used to disable this automatic conversion. If Foo is defined as follows:

class Foo {
public:
explicit Foo (const Bar &);
// more stuff
};

then silent conversions like that won't occur, and calling snarf_the_foo with a Bar argument will result in a compiler error. You can still use an explicit cast--i.e. snarf_the_foo (Foo(b)) if you want to do that.


CategoryCpp