2

I'm having difficulty defining and using a conversion operator to a base class. Consider the following:

class base 
{
public:
    base(const base&);
    base& operator=(const base&);
    //some stuff
};
class child : public base
{
public:
    operator base() const;
    //some more stuff
};

int main()
{
    child c;
    base b=c;
    b=c;
}

If I attempt to convert a child to a base, operator base() is never called (even if I make the conversion explicit). Instead, the copy constructor or assignment operator from the base class is called directly, without a conversion.

How can I cause operator base() to be called when a child is assigned (or copy-constructed) to a base?

IanPudney
  • 5,941
  • 1
  • 24
  • 39

1 Answers1

6

A conversion function to a base class is syntactically legal, but it will never be called. From standard draft n3337:

12.3.2 Conversion functions [class.conv.fct] §1

[...] A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void. [...]

The language has got different mechanism for conversions from derived to base. Read about object slicing. To put it simply - it's done automatically for you.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141
  • Thanks. I feel like C++ should call such a conversion operator if you define one instead of slicing (which is effectively "default conversion"); is there any particular reason it doesn't? – IanPudney Mar 21 '14 at 18:34
  • Thinking about it, what else can you do in such a function than to get rid of the derived portion of the object? The languages value semantics leave no other choice and we have references for cases when we need to refer to derived classes through base class interfaces. I suppose you could have other side effects in such conversion, but that would be smelly to say the least and there are better ways to do that. – jrok Mar 21 '14 at 18:39
  • 1
    @jrok You could use this to disambiguate which base to convert to when you inherit from the same base class in an inheritance chain (diamond of death) – DarthRubik Oct 09 '18 at 19:06