Question

Have seen some related questions, but not this exact one...

I've treated classes as fitting into a few major categories, let's say these four for simplicity:

  • Value Classes which have some data and a bunch of operations. They can be copied and meaningfully compared for equality (with copies expected to be equal via ==). These pretty much always lack virtual methods.

  • Unique Classes whose instances have identity that you disable assignment and copying on. There's usually not an operator== on these because you compare them as pointers, not as objects. These quite often have a lot of virtual methods, as there isn't risk of since you're being forced to pass them by pointer or reference.

  • Unique-but-Clonable Classes which disable copying, but are pre-designed to support cloning if that's what you really want. These have virtual methods, most importantly those following the virtual construction / cloning idiom

  • Container Classes which inherit the properties of whatever they're holding. These tend not to have virtual methods...see for instance "Why don't STL containers have virtual destructors?".

Regardless of holding this informal belief system, a couple times I've tried adding a virtual method to something copyable. While I may have thought it would "be really cool if that worked", inevitably it breaks.

This led me to wonder if anyone has an actual good example of a type which has virtual methods and doesn't disable copying?

Was it helpful?

Solution 2

There's nothing inherently wrong in being able to copy a polymorphic class. The problem is being able to copy a non-leaf class. Object slicing will get you.

A good rule of thumb to follow is never derive from a concrete class. This way, non-leaf classes are automatically non-instantiable and thus non-copyable. It won't hurt to disable assignment in them though, just to be on the safe side.

Of course nothing is wrong with copying an object via a virtual function. This kind of copying is safe.

Polymorphic classes are normally not "value-classes" but it does happen. std::stringstream comes to mind. It'not copyable, but it is movable (in C++11) and moving is no different from copying with regard to slicing.

OTHER TIPS

The only counter-example that I have are classes that are meant to be stack-allocated and not heap-allocated. One scheme I use it for is Dependency Injection:

class LoggerInterface { public: virtual void log() = 0; };

class FileLogger final: public LoggerInterface { ... };

int main() {
    FileLogger logger("log.txt");

    callMethod(logger, ...);
}

The key point here is the final keyword though, it means that copying a FileLogger cannot lead to object-slicing.

However, it might just be that being final turned FileLogger into a Value class.

Note: I know, copying a logger seems weird...

Virtual dispatch happens a runtime. The only reason one should want it is when the actual, dynamic type of an object cannot be known until runtime. If you already knew the desired dynamic type when writing the program, you could use different, non-virtual techniques (such as templates, or non-polymorphic inheritance) to structure your code.

A good example for the need for runtime typing is parsing I/O messages, or handling events – any kind of situation where one way or another you'll either have some sort of big switch table to pick the correct concrete type, or you write your own registration-and-dispatch system, which basically reinvents polymorphism, or you just use virtual dispatch.

(Let me interject a warning: Many people misuse virtual functions to solve problems that don't need them, because they're not dynamic. Beware, and be critical of what you see.)

With this said, it's now clear that your code will be dealing mostly with the polymorphic base classes, e.g. in function interfaces or in containers. So let's rephrase the question: Should such a base class be copyable? Well, since you never have actual, most-derived base objects (i.e. the base class is essentially abstract), this isn't really an issue, and there's no need for this. You've already mentioned the "clone" idiom, which is the appropriate analogue of copying in a polymorphic.

Now, the "clone" function is necessarily implemented in every leaf class, and it necessarily requires copying of the leaf classes. So yes, every leaf class in a clonable hierarchy is a class with virtual functions and a copy constructor. And since the copy constructor of a derived class needs to copy its base subobjects, all the bases need to be copyable, too.

So, now I believe we've distilled the problem down to two possible cases: Either everything in your class hierarchy is completely uncopyable, or your hierarchy supports cloning, and thus by necessity every class in it is copyable.

So should a class with virtual functions have a copy constructor? Absolutely. (This answers your original question: when you integrate your class into a clonable, polymorphic hierarchy, you add virtual functions to it.)

Should you try to make a copy from a base reference? Probably not.

Not with a single, but with two classes:

#include <iostream>
#include <vector>
#include <stdexcept>

class Polymorph
{
    protected:
    class Implementation {
        public:
        virtual ~Implementation() {};
        // Postcondition: The result is allocated with new.
        // This base class throws std::logic error.
        virtual Implementation* duplicate() {
             throw std::logic_error("Duplication not supported.");
        }

        public:
        virtual const char* name() = 0;
    };

    // Precondition: self is allocated with new.
    Polymorph(Implementation* self)
    :   m_self(self)
    {}

    public:
    Polymorph(const Polymorph& other)
    :   m_self(other.m_self->duplicate())
    {}

    ~Polymorph() {
        delete m_self;
    }

    Polymorph& operator = (Polymorph other) {
        swap(other);
        return *this;
    }

    void swap(Polymorph& other) {
        std::swap(m_self, other.m_self);
    }

    const char* name() { return m_self->name(); }

    private:
    Implementation* m_self;
};

class A : public Polymorph
{
    protected:
    class Implementation : public Polymorph::Implementation
    {
        protected:
        Implementation* duplicate() {
            return new Implementation(*this);
        }

        public:
        const char* name() { return "A"; }
    };

    public:
    A()
    :   Polymorph(new Implementation())
    {}
};

class B : public Polymorph {
    protected:
    class Implementation : public Polymorph::Implementation {
        protected:
        Implementation* duplicate() {
            return new Implementation(*this);
        }

        public:
        const char* name() { return "B"; }
    };

    public:
    B()
    :   Polymorph(new Implementation())
    {}
};


int main() {
    std::vector<Polymorph> data;
    data.push_back(A());
    data.push_back(B());
    for(auto x: data)
        std::cout << x.name() << std::endl;
    return 0;
}

Note: In this example the objects are copied, always (you may implement shared semantics, though)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top