Virtual copy constructor of C++ technology

1. The grammatical rules of virtual function return type

When a subclass (derived class) implements a virtual function of the parent class (base class), it is no longer necessary to declare the same return type as the original one. If the return type of the function is a pointer or reference to the parent class (base class), the function of the subclass (derived class) can return a pointer or reference to a derived class of the parent class (base class) .

2. Sample

#include <list>


struct NLComponent
{
    virtual NLComponent* clone() const = 0;
    // ...
};

struct TextBlock : NLComponent
{
    virtual TextBlock* clone() const override 
    {
        return new TextBlock(*this);
    }

    // ...
};

struct Graphic : NLComponent
{
    virtual Graphic* clone() const override 
    {
        return new Graphic(*this);
    }
    // ...
};


struct NewsLetter
{
    NewsLetter() = default;
    // 实现任何对象的copy
    NewsLetter(const NewsLetter& rhs)
    {
        for(auto& component : rhs.components)
        {
            components.push_back(component->clone());
        }
    }

    void add(NLComponent* component)
    {
        components.push_back(component);
    }

private:
    std::list<NLComponent*> components;
};


int main()
{
    NewsLetter newsLetter;
    newsLetter.add(new TextBlock());
    newsLetter.add(new Graphic());

    // copy
    NewsLetter backup(newsLetter);

    return 0;
}

By using the return value rules of virtual functions, NewsLetter can copy any objects aggregated by NewsLetter.

 

Guess you like

Origin blog.csdn.net/xunye_dream/article/details/115036123