Maintaining polymorphism of copies

Started by
5 comments, last by MaulingMonkey 17 years ago
Okay, am I being really stupid here or what? I have a class that stores a pointer or reference to a base class. This class has a setter method for this member variable, which accepts a pointer or reference to a base class. I want this method to make a copy of the pointed-to object, and store a pointer to the copy, in order to be able to cast to derived types later. Can I do something like below, or will the object be sliced? I'm fairly sure it will, so what should I be doing instead? I know this is very simple, but my brain's gone numb.

class MyClass {
public:
    void set(Base* var) {
        m_var = new Base(*var));
    }

private:
    Base* m_var;
};

Advertisement
Is there a reason you're trying to implement your own inheritance? Why not just derive MyClass from Base? Or is this not really supposed to be a base class?
No, that won't work. It'll create a new Base object that copies the Base properties of the passed object. It will not create a derived class instance.

The common method for doing things like this is to implement a pure virtual clone method in the Base class interface:

class Base{public:    virtual Base *clone() = 0;};class Derived : public Base{public:    virtual Base *clone();}Base *Derived::clone(){    return new Derived(this);}


As a side note, generally if you are upcasting from base to derived there is something wrong with your architecture.

-me
Palidine: your approach is the correct one, but why is the base version of the clone function pure virtual?
Paladine: Thanks, that's perfect. I've always wondered what these mysterious 'clone()' methods I've seen were for :)

Also, I'm well aware that the architecture I'm using is rubbish, it's just too late in the project to change it! "if it works..." and all that.
Ooh, lightning quick question: do you mean "return new Derived(*this);" - '*this' instead of 'this'?
Quote:Original post by hymerman
Ooh, lightning quick question: do you mean "return new Derived(*this);" - '*this' instead of 'this'?


Yes.

This topic is closed to new replies.

Advertisement