I have the following classes
class abc
{
private:
string name_;
public:
explicit abc(string name);
};
class xyz
{
private:
abc obj_abc_;
public:
xyz ():obj_abc_("NOTHING") { }; //I think this should give an error since explicit is used.
};
According to what i have understood about explicit, i should be getting a compiler error whenever xyz constructor is being called; because i am initializing the obj_abc by simply assigning it to a string. But i am not getting any compiler error here. What am i missing?
expliciton a constructor means that the constructor can't be used for conversion from its parameter type to the class type. So an implicit conversionwill be forbidden if the constructor is
explicit, but not otherwise. An explicit conversionwill be allowed in either case. In your case, direct initialisation in an initialiser list is explicit; so your explicit constructor can be used for that.
explicitdoesn't prevent implicit conversions to the constructor parameter's type; so the conversion from"NOTHING"tostringin your example is allowed in either case, using the non-explicitstringconstructor.