0

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?

1
  • explicit abc(string name):name_(name); This compiled? Commented Dec 12, 2014 at 15:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.