Copy object - keep polymorphism

By : MOnsDaR
Source: Stackoverflow.com
Question!

The following code tries to copy an object and keep the original type. Unfortunately it does not work (every copied object will become a Super instead of being of the same class as its original).

Please note that copySuper(const Super& givenSuper) should not know anything about the subclasses of Super.

Is it possible to do such a copy? Or do I have to change the definition of copySuper ?

#include <string>
#include <iostream>

class Super
{
public:
    Super() {};
    virtual ~Super() {};

    virtual std::string toString() const
    {
        return "I'm Super!";
    }
};

class Special : public Super
{
public:
    Special() {};
    virtual ~Special() {};

    virtual std::string toString() const
    {
        return "I'm Special!";
    }
};

Super* copySuper(const Super& givenSuper)
{
    Super* superCopy( new Super(givenSuper) );
    return superCopy;
}

int main()
{
    Special special;
    std::cout << special.toString() << std::endl;

    std::cout << "---" << std::endl;

    Super* specialCopy = copySuper(special);
    std::cout << specialCopy->toString() << std::endl;

    return 0;
}

//Desired Output:
// # I'm Special!
// # ---
// # I'm Special!
//
//Actual Output:
// # I'm Sepcial!
// # ---
// # I'm Super!
By : MOnsDaR


Answers

Just for the record, this is in the C FAQ:

http://www.parashift.com/c -faq-lite/abcs.html#faq-22.5



What you want is generally implemented using an abstract clone method in the base class. Special will typically implement this method by returning new Special(*this).

Also note that it is considered a best practice to make base classes uncopyable.

By : icecrime


This is what you need :

class Super
{
    public:
        Super()
        {
        }

        virtual Super* clone() const
        {
            return( new Super(*this) );
        };
};


class Special : public Super
{
    public:
        Special() : Super()
        {
        };
        Special(const Special


This video can help you solving your question :)
By: admin