newbie question about constructor

R

Rolf Magnus

sam said:
Hi,
Why declare constructors implicit or explicit ,whats the use of it?

Constructors that can be called with one argument are conversion
constructors. If the constructor is not declared 'explicit', the compiler
will do implicit conversions using that constructor.

struct X{};
struct Y{};

class MyClass
{
public:
MyClass(X);
explicit MyClass(Y);
};

void myfunc(MyClass);

int main()
{
X x;
Y y;

myfunc(x); // ok, conversion constructor is implicitly used
myfunc(y); // error, constructor is explicit
myfunc(static_cast<MyClass>(y)); // ok, explicit conversion
}

Btw: What C++ book are you reading that doesn't explain this?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top