adamm adamm - 9 days ago 5
C++ Question

C++ - Change object pointed by base class (in an operator oveloading function returning reference to base class)

I have one abstract class

class Abs{
//...
public:
virtual Abs& operator--() = 0;
virtual void print() = 0;
};


and two subclasses

class Sub1: public Abs{
//...
public:
Abs& operator--() {return *this} //this is just to prevent
//Sub1 to become an abstract class
void print() {cout<<"Sub1"<<endl;}
};

class Sub2: public Abs{
//...
public:
Abs& operator--() {...} //here is an issue
void print() {cout<<"Sub2"<<endl;}
};


Is it somehow possible to overload operator-- in Sub2 so that in main function ptr now pointing to an object of type Sub1?

int main()
{
Abs* ptr;
Sub2 sub2;
ptr=&sub2;

ptr->print(); //this should print "Sub2"

--(*ptr);

ptr->print(); //this should print "Sub1"

return 0;
}

Answer

First, you're requirement is awkward, and the real answer is: rethink what you're trying to do.

What you're basically asking for is a way for a member function to change this so that it points on another object (since you can't change an object's type). This is impossible.

A slightly more reasonable solution is to avoid the direct use of polymorphism, and have the pointed object contain a field that will point to either Sub1 or Sub2. Then, have that pointer object direct calls to that field. This way, you can change the effective type you're using without hitting language limitations. Note that the pointed object would not be an Abs, of course, but some other type.