0

If I have code like the following:

class Base { /* ... */};
class Derived : public Base { /* ... */ };

 int main() {
    Base b = Derived{};
 }

Then the code exhibits the slicing problem. Any data that is part of class Derived but not part of class Base is lost. But suppose that Derived doesn't have any data members or base classes that aren't in Base, so there is no data to lose.

Does this code still exhibit undefined behavior or other problems?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Joe Gottman
  • 356
  • 2
  • 2
  • No, there's no undefined behavior here. –  Nov 22 '14 at 02:17
  • Slicing doesn't cause undefined behavior. It's simply what happens when you copy a derived class into a base class object - you lose the "derivedness". – David G Nov 22 '14 at 02:20
  • In this example, you could simply make the type of B derived, as you know it. – Neil Kirk Nov 22 '14 at 02:22
  • 1
    There is no data to lose, but don't forget virtual functions to lose. – Neil Kirk Nov 22 '14 at 02:22
  • The only question here would be: why would you need a derived class that is completely identical to its base? I realize you're asking a theoretical question, but still. – striving_coder Nov 22 '14 at 02:23

1 Answers1

4

Normally speaking slicing doesn't have undefined behavior: It usually just doesn't do what you WANT it to do. In this case I can't see any problems, although I also can't see why you would need a child class that didn't add anything to the base.

Mark B
  • 95,107
  • 10
  • 109
  • 188
  • One use case would be if you have read-only handle and mutating handle classes. It makes sense that mutating handle extends the read-only one while only adding functionality (and no data members). – rburny Oct 05 '16 at 06:38
  • @rburny Unless I'm missing something (which is possible) a "writable handle" fails both the is-a and substitutability tests for inheritance. – Mark B Oct 05 '16 at 12:06
  • I don't see the problem. "Writable handle" can be used as a "readonly handle" if you only use const methods. It's "writable", not "write-only". – rburny Oct 05 '16 at 14:25