0

I have an abstract base class and I have to implement pure virtual post and pre increment operators because of homework.

virtual Base & operator ++ () = 0;
virtual Base operator ++ (int ignore) = 0;

There is a slicing problem. What should I do for implementing derived class definition. Template is not a solution this homework because that is not fit the whole homework.

YSC
  • 38,212
  • 9
  • 96
  • 149
scylla
  • 23
  • 3
  • 1
    What do you mean _"There is a slicing problem."_, can you elaborate that [in your question](https://stackoverflow.com/posts/53912092/edit) please? – πάντα ῥεῖ Dec 24 '18 at 10:23
  • 1
    Someone is in charge of this homework, no? Tell them their task has fundamental issues – StoryTeller - Unslander Monica Dec 24 '18 at 10:26
  • At this operators, I change member of derived class. But I can't access it. I tried to use pointers but, slicing problem occurs. – scylla Dec 24 '18 at 10:27
  • You may put the corresponding member variable into the bass class though. I don't know in which circumstances makes sense, but well. Best would be you provide a [mcve] to show what you've tried so far, and where the problem occurs. – πάντα ῥεῖ Dec 24 '18 at 10:30
  • https://stackoverflow.com/questions/7579371/inheritance-and-invalid-covariant-return-type-error-on-operator-overloading – Hans Passant Dec 24 '18 at 10:42

1 Answers1

1

Indeed, in a derived class this postfix increment operator would lead to a sliced object.

struct Base
{
    virtual Base& operator++()   = 0;
    virtual Base operator++(int) = 0;
};

struct Derived : Base
{
    void inc();
    virtual Base& operator++ ()  { inc(); return *this; }                   // no slicing
    virtual Base operator++(int) { auto self = *this; inc(); return self; } // slicing
};

What should I do for implementing derived class definition.

My opinion is that a virtual operator is a red flag and a design flaw. Avoid it if possible.

If, "because of homework" you're stuck with it, you could temper with its return type and craft a non-canon postfix operator.

#include <memory>
struct Base
{
    virtual Base&                 operator++()    = 0;
    virtual std::unique_ptr<Base> operator++(int) = 0;
};

This will come as a great (I mean strong, not good) surprise to the class user:

void f(Derived&);
Derived d;
f(*d++); // this is *weird*
YSC
  • 38,212
  • 9
  • 96
  • 149