In C++ it is possible to declare constructors for a class, taking a single parameter, and use those constructors for doing type conversion.
A declaration like: 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
class A { public: A(int); }; void main() { A a1=37; }
A declaration like: 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
}
No comments:
Post a Comment