//Vars to know about
Square* square;
vector<Shape> shapes;

I'm trying to add things that are shapes, or in this instance square (which inherits from shape), but whenever I call shapes.push_back(square), I get this error message:

draw.cpp:55: error: request for member ‘push_back’ in ‘shapes’, which is of non-class type ‘std::vector<Shape, std::allocator<Shape> >*’
draw.cpp:57: error: request for member ‘size’ in ‘shapes’, which is of non-class type ‘std::vector<Shape, std::allocator<Shape> >*’

Dani AI

Generated

’s pointer-based suggestion fixes the immediate compile error, but there are a few important follow-ups to avoid subtle bugs and leaks when you move from a toy example to real code.

Storing derived objects by value in a container of base type causes object slicing: the derived part is discarded and virtual dispatch won’t work. For polymorphic containers prefer pointer-like ownership; in modern C++ that means storing owning smart pointers so lifetime is automatic and safe. Example pattern:

// base has a virtual destructor and virtual behavior
struct Shape { virtual void draw() = 0; virtual ~Shape() = default; };
struct Square : Shape { void draw() override { /* ... */ } };

std::vector<std::unique_ptr<Shape>> shapes;
shapes.emplace_back(std::make_unique<Square>());
for (const auto &s : shapes) s->draw();

Use std::unique_ptr when each container element has a single owner; use std::shared_ptr only if you truly need shared ownership. If you need copyable semantics for polymorphic types, implement a clone() virtual that returns a std::unique_ptr<Shape> and copy via that. Always ensure the base class destructor is virtual so deleting through a base pointer is well defined.

References and further reading: object slicing (why value storage loses derived info) is explained at Object slicing. The C++ smart-pointer utilities and make_unique are documented at std::unique_ptr and make_unique. For destructor rules see the destructor language notes at .

Small troubleshooting tips: if the compiler says your vector<...> is a pointer type (notice a trailing * in the type), either dereference it when calling methods or change the declaration to an actual container object. Avoid raw new/delete in containers unless you have a very good reason.

Recommended Answers

All 2 Replies

The vector isn't expecting a pointer. Change the vector to this if you want pointers: vector<Shape*> shapes;

Yay! No errors!! Silly, pointers... still getting used to where to put the * and where not to.

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.