C ++ Why is the converter constructor implicitly called?

Why is the child class constructor constructor called in the code below?

I mean, it automatically converts Base to Child through the constructor of the Child converter. The code below compiles, but shouldn't it compile since I did not provide bool Child::operator!=(Base const&)?

class Base
{
};

class Child : public Base
{
public:
  Child() {}
  Child(Base const& base_) :
    Base(base_)
  {
    std::cout <<"should never called!";
  }
  bool operator!=(Child const&)
  {
    return true;
  }
};

void main()
{
  Base  base;
  Child child;

  if(child != base)
    std::cout << "not equal";
  else
    std::cout << "equal";
}
+3
source share
4 answers

Because you provided a conversion constructor. If you do not want the compiler to automatically convert objects Baseto Childusing

Child(Base const& base_)

make it explicit:

explicit Child(Base const& base_)

Thus, the constructor will only be called when you explicitly specify it in contexts such as:

Child ch(base);
foo(Child(base));
new Child(base);
+3
source

Child(Base const& base_) ( ). , , main. , explicit.

+6

Child - . , , . :

class Child : public Base
{
public:
  Child() {}
  explicit Child(Base const& base_) :
    Base(base_)
  {
    std::cout <<"should never called!";
  }
  bool operator!=(Child const&)
  {
    return true;
  }
};

, .

+1

Since you are not providing any operator! = () That takes a Base argument as an argument: the compiler will try “what it can” and see that there is a conversion constructor for the type of argument (Child) that can be called. So he uses it to do! = Work.

0
source

Source: https://habr.com/ru/post/1737066/


All Articles