0

I have an assignment that doesn't allow me to use the vector class. I have a base class called Shape and different derived class such as Rectangle and Circle and i have to create my own vector class that has a dynamic array which can hold all these different shapes. I have used the following method that seems to work well

 int **shape=new int*[capacity]; 

My problem comes with the "add_shape" function. I know how to add a shape individually using for example:

shape[0]=new Rectangle(); shape[1]=new Circle(); 

But how would one go about creating a universal function for adding a shape that could either be a rectangle or circle for instance.

1
  • MyVector<std::unique_ptr<BaseClass>>? Commented Jan 28, 2018 at 4:34

2 Answers 2

2

Just wanted to elaborate on Nicky C's comment.

#include <memory> using namespace std; class Shape {}; class Rectangle : public Shape {}; class Circle : public Shape {}; template <class Type> class MyVector {}; // implement (with push method, etc.) int main() { MyVector<unique_ptr<Shape>> v; v.push(unique_ptr<Shape>(new Rectangle())); v.push(unique_ptr<Shape>(new Circle())); return 0; } 

The vector contains elements of type unique_ptr<Shape> which is the base class. Each element of the vector can be unique_ptr<Rectangle> or unique_ptr<Circle> as well. However, if the vector were of type unique_ptr<Rectangle>, each element would have to be of type unique_ptr<Rectangle> (i.e. it could not be of type unique_ptr<Circle>).

Since you are allocating memory on the heap, using unique_ptr just makes sure that you don't need to call delete yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

One of the strengths of inheritance/polymorphism is that you can use a derived class wherever a base class is needed. It is an important key concept. For instance, as in your code above, you can do:

Shape *s = new Shape(); s = new Rectangle(); s = new Circle(); 

This also applies to function parameters:

class DynamicArray { private: Shape **_shapes[]; ... public: void add_shape(Shape *s) { // Add the shape to _shapes; } ... }; void main() { DynamicArray array; array.add_shape(new Shape()): array.add_shape(new Rectangle()): array.add_shape(new Circle()): } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.