fbpx

A special note about the C++ explicit keyword to disable implicit constructor

(Last Updated On: May 19, 2010)

A special note about the C++ explicit keyword to disable implicit constructor
A a1 = 37;
says to call the A(int) constructor to create an A object from the integer value. Such a constructor is called a “converting constructor”.
However, this type of implicit conversion can be confusing, and there is a way of disabling it, using a new keyword “explicit” in the constructor declaration:
class A {
public:
explicit A(int);
};

void f(A) {}

void g()
{
A a1 = 37; // illegal

A a2 = A(47); // OK

A a3(57); // OK

a1 = 67; // illegal

f(77); // illegal
}
Using the explicit keyword, a constructor is declared to be
“nonconverting”, and explicit constructor syntax is required:

class A {
public:
explicit A(int);
};

void f(A) {}

void g()
{
A a1 = A(37);

A a2 = A(47);

A a3(57);

a1 = A(67);

f(A(77));
}
Note that an expression such as:
A(47)
is closely related to function-style casts supported by C++. For example:
double d = 12.34;

int i = int(d);

This post has been presented by http://www.glenmccl.com/tip_023.htm

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top