Mosi Mosi - 1 month ago 6
C++ Question

defining explicit overloaded constructor issue

I have following class that some of the operators are overloaded:

class CLASS1
{
CLASS1();
CLASS1(const CLASS1 &obj);

CLASS1 operator +(const CLASS1 &obj) {
CLASS1 srcObj;
// doing add stuff here
return srcObj;
}

void func()
{
CLASS1 boj = // some method which returns CLASS1 obj.
}


CLASS1& operator =(const CLASS1 &obj) {
// copy properties
}
}


Ok, this works fine. but after awhile I decided to make my class explicit to avoid implicit conversions. Therefore, I've made it this way:

class CLASS1
{
explicit CLASS1();
explicit CLASS1(const CLASS1 &obj);

CLASS1 operator +(const CLASS1 &obj) {
CLASS1 srcObj;
// doing add stuff here
return srcObj; // compiler gives non-matching errors
}

void func() {
CLASS1 boj = somemethods(); // compiler gives non-matching errors
}

CLASS1& operator =(const CLASS1 &obj) {
// copy properties
}
}


Now, the compiler gives 'no matching function to call...' error (specified in the code above), in spite of I've explicitly overloaded assignment operator. Where is my mistake?

Answer

When you return an object by value the copy-constructor is called implicitly. If you say it's not allowed to be called implicitly you will get an error.

You should not use explicit for your default, copy or move constructors. Or for constructors taking more than one argument. Only for constructors taking a single argument (with the noted exceptions).