Titone Maurice Titone Maurice - 27 days ago 10
C++ Question

Why is my constructor being called when I assign two objects of that class?

I am so confused, and I'm sorry if this is obvious. Am I wrong that in the following:

struct MyStruct
{
MyStruct(){};
MyStruct(MyStruct* arg){};
}


MyStruct(MyStruct* arg){}; is a constructor taking one pointer to a MyStruct as argument?

Because I have a problem that this constructor (which I think it is) is being called when I do this:

int main()
{
MyStruct obj;
MyStruct* objPtr;
obj = objPtr;

return 0;
}


When assigning obj to objPtr I expected the compiler to complain, but it doesn't, and instead calls MyStruct(MyStruct* arg); which I thought was a constructor taking a pointer argument.

Any help would be appreciated. Also, if I add a copy assignment operator to the class it still happens.

Edit: Thanks for the answers. It looks like I've got some reading to do on this, and the topic seems to be (for anyone wondering) converting constructors in C++. Also I'm guessing the explicit keyword. Here is a link to an SO question which explains it:

What is a converting constructor in C++ ? What is it for?

Answer
  1. The compiler synthesizes an assignment operator for you:

    MyStruct& MyStruct::operator=(MyStruct const&) = default;
    
  2. When it sees the assignment, it finds a candidate for the operator (which is the one it created). Then it sees that it can use your constructor to make a conversion, to a type that will allow the assignment (MyStruct). So it boils down to:

    obj = MyStruct (objPtr);
    

If you want to see the error happen, mark you constructor as explicit:

struct MyStruct
{
   MyStruct(){};
   explicit MyStruct(MyStruct* arg){};
}
Comments