Search code examples
c++cloneassignment-operator

Implementing a non-public assignment operator with a public named method?


It is supposed to copy an AnimatedSprite. I'm having second thoughts that it has the unfortunate side effect of changing the *this object.

How would I implement this feature without the side effect?

EDIT:

Based on new answers, the question should really be: How do I implement a non-public assignment operator with a public named method without side effects? (Changed title as such).

public:
AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) {
    return (*this = animatedSprite);
}

protected:
AnimatedSprite& AnimatedSprite::operator=(const AnimatedSprite& rhs) {
    if(this == &rhs) return *this;

    destroy_bitmap(this->_frameImage);
    this->_frameImage = create_bitmap(rhs._frameImage->w, rhs._frameImage->h);
    clear_bitmap(this->_frameImage);
    this->_frameDimensions = rhs._frameDimensions;
    this->CalcCenterFrame();
    this->_frameRate = rhs._frameRate;
    if(rhs._animation != nullptr) {
        delete this->_animation;
        this->_animation = new a2de::AnimationHandler(*rhs._animation);
    } else {
        delete this->_animation;
        this->_animation = nullptr;
    }

    return *this;
}

Solution

  • You can call the private assignment operator:

    public:
    AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) {
        return ( operator=(animatedSprite));
    }
    

    There is no getting around modifying this if you are trying to do assignment

    Typically, clone returns a pointer or smart pointer to a new instance:

    struct IFoo {
      virtual IFoo* clone() const = 0;
    };
    struct Foo1 : public virtual IFoo {
      virtual IFoo* clone() { return new Foo1(this);}
    };
    struct Foo2 : public virtual IFoo {
      virtual IFoo* clone() { return new Foo2(this);}
    };
    
    IFoo* foo0 = new Foo1();
    ...
    IFoo* fooClone = foo0.clone();