-1

Assume I have:

class A {
int i;
}

class B : public A {
int j;
A base() { return *this; }
}

Is this legal C++ ? Or will I run into slicing problems?

lezebulon
  • 7,607
  • 11
  • 42
  • 73
  • 2
    This is slicing. Why would you think it isn't? – 1201ProgramAlarm Nov 27 '20 at 22:03
  • Not a problem. But you technically don't need that `base` method. You can simply say `A a = b;` and it will implicitly cast. In almost all uses something that expects an instance of `A` will gladly accept an instance of the derived class `B`. – selbie Nov 27 '20 at 22:07
  • I'm trying to understand what ctor is being called here, as it seems that my compiler is making a new instance of type A – lezebulon Nov 27 '20 at 22:10
  • See [What is object slicing?](https://stackoverflow.com/questions/274626/what-is-object-slicing). – 1201ProgramAlarm Nov 27 '20 at 22:12
  • Yes, it is legal C++, in the sense that no diagnostic is required. Yes, it does object slicing. Whether the slicing causes problems depends on what your code, which uses these classes, does with the objects. – Peter Nov 27 '20 at 23:47

1 Answers1

2

Is this legal C++ ?

Yes.

Or will I run into slicing problems?

Slicing is exactly what is being done here. Whether there is a problem or not is subjective.

There is not explicit constructor

There is no need for an explicit constructor since the copy constructor is generated implicitly.

eerorika
  • 232,697
  • 12
  • 197
  • 326