Initialization list (Constructor): ERROR parameter conversion not allowed

 

Hi there, could someone point out what's preventing this simple code to compile?


struct ValueStruct {
  string field1;
  
  ValueStruct(string f1) : field1(f1) {};
};

class Complex3ValueStruct {
  public:
    ValueStruct mVs;
    
    Complex3ValueStruct(ValueStruct& valueStruct)
	: mVs(valueStruct) {}        // compilation ERROR on this line!
};


The compiler tells first an ERROR, then a warning:

ERROR: 'valueStruct' - parameter conversion not allowed

WARN: implicit conversion from 'number' to 'string'


Both on the list initializer line:

: mVs(valueStruct) {}


I don't want to declare default constructors, so how could I make the above to compile?

And most important, how would I make this toy example work/compile with 3rd party classes I do not own? -I need to put an object of 3rd party class inside another object of my own.


Thanks!

 

If you're initializing a field with another struct of the same type, then you need a copy constructor:

struct ValueStruct {
  string field1;
  
  ValueStruct(string f1) : field1(f1) {};
  ValueStruct(const ValueStruct& other) : field1(other.field1) {}
};

In your case this would also work since that's the constructor the struct has (but I prefer doing the above one):

class Complex3ValueStruct {
  public:
    ValueStruct mVs;
    
    Complex3ValueStruct(string valueString)
        : mVs(valueString) {}
};
 
Manuel Alejandro Cercos Perez #:

If you're initializing a field with another struct of the same type, then you need a copy constructor:

In your case this would also work since that's the constructor the struct has (but I prefer doing the above one):

Thank you! I see my mistake, I thought that this `mVs(...)` would act as a kind of magic assignment, but I realize now that it is a call to the constructor of `ValueStruct`, so it needs to match the arguments.


My original problem was to define own classes to hold 3rd party object instances, that's why I made that toy example, as I was getting the same problem. Which I fixed by storing an object pointer of the 3rd party object inside my object. BUT I'm not still 100% sure this is the way to go... Because I cannot create copy constructors for classes I do not own.


Thanks @Manuel Alejandro Cercos Perez