Composition using a link or a pointer?

Please let me know which one is good

I have a class like this

class Shape
{
public:
    virtual void Display()
    {
        cout << "Shape::Display()" << endl;
    }
};

class Line : public Shape
{
public:
    void Display()
    {
        cout << "Line::Display()" << endl;
    }
};

class Circle : public Shape
{
public:
    void Display()
    {
        cout << "Circle::Display()" << endl;
    }
};

1)

class Container
{
public:
    Container(Shape& shape) : m_Shape(shape)
    {

    }

    void Draw()
    {
        m_Shape.Display();
    }
private:
    Shape& m_Shape;
};

Here he takes the link and assigns it to the base class object.

2)

class ShapeContainer
{
public:
    ShapeContainer(Shape* pShape) : m_pShape(pShape)
    {

    }
    void Draw()
    {
        m_pShape->Display();
    }

private:
        Shape* m_pShape;
};

Here he takes a pointer and assigns it to a base class object.

Please let me know which one is good or when to use them.

+3
source share
4 answers

The decision must be made in terms of what you want to do with your object. Since you do not enable the option to save the value, I assume that you need the container to refer to an external object. If this is not a requirement, consider using standard containers: keep a copy of the object.

, NULL ( : , Undefined Behavior). , , , : , .

, , , reset . , , , , . , , . - : .

, , NULL, / . , , , . , . , , ( ) . , ( , , ).

+7

, . NULL- , NULL. BTW, shape .

+1

, , , . NULL , , . 10 , , NULL, .

, , .

.

+1

I would go for a reference approach if there is no need to explicitly control the lifetime of the contained object in the container class, and you can be sure that the passed reference object is always valid during the life of the container class.

0
source

Source: https://habr.com/ru/post/1794071/


All Articles