Not getting the expected behavior with "explicit" keyword in c++

96 views Asked by At

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?

2

There are 2 answers

0
Mike Seymour On BEST ANSWER

explicit on a constructor means that the constructor can't be used for conversion from its parameter type to the class type. So an implicit conversion

abc x = "NOTHING";

will be forbidden if the constructor is explicit, but not otherwise. An explicit conversion

abc x("NOTHING");

will 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.

explicit doesn't prevent implicit conversions to the constructor parameter's type; so the conversion from "NOTHING" to string in your example is allowed in either case, using the non-explicit string constructor.

0
AudioBubble On

Besides the syntax error (use { } instead of ;) you aren't assigning or implicitly converting anything. You're explicitly constructing the object in the initialisation list.