Jump to content
  • Advertisement
Sign in to follow this  
hymerman

Maintaining polymorphism of copies

This topic is 4132 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
};

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Palidine: your approach is the correct one, but why is the base version of the clone function pure virtual?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!