Search code examples
c++stackvirtualabstract-classderived-class

Using an abstract class to implement a stack of elements of the derived class


I have to do this for a basic C++ lecture at my university, so just to be clear: i would have used the STL if i was allowed to.

The Problem: I have a class named "shape3d" from which i derived the classes "cube" and "sphere". Now i have to implement "shape3d_stack", which is meant be able of holding objects of the types "cube" and "sphere". I used arrays for this and it worked quite well when i tried to do so with a stack of ints. I tried to do it like so:

shape3d_stack.cpp:

15    // more stuff
16    
17        shape3d_stack::shape3d_stack (unsigned size) :
18         array_ (NULL),
19         count_ (0),
20         size_  (size)
21        { array_ = new shape3d[size]; }
22    
23    // more stuff

but, unfortunately, the compiler tells me:

g++ -Wall -O2 -pedantic -I../../UnitTest++/src/ -c shape3d_stack.cpp -o shape3d_stack.o
shape3d_stack.cpp: In constructor ‘shape3d_stack::shape3d_stack(unsigned int)’:
shape3d_stack.cpp:21: error: cannot allocate an object of abstract type ‘shape3d’
shape3d.hpp:10: note:   because the following virtual functions are pure within ‘shape3d’:
shape3d.hpp:16: note:  virtual double shape3d::area() const
shape3d.hpp:17: note:  virtual double shape3d::volume() const

i guess this must be some kind of really ugly design error caused by myself. so how would be the correct way of using all kinds of objects derived from "shape3d" with my stack?


Solution

  • You can't create objects from abstract classes.
    You'll probably want to create an array of pointers to the abstract class, which is allowed, and fill them with derived instances:

    // declaration somewhere:
    shape3d** array_;
    
    // initalization later:
    array_ = new shape3d*[size];
    
    // fill later, triangle is derived from shape3d:
    array_[0] = new triangle;