Base class of non-polymorphic derived classes

I have the following class definitions:

class BaseHandle { /* Lots of things */ };
class VertexHandle : public BaseHandle {
    /* Only static members and non-virtual functions, default dtor */ };
class EdgeHandle : public BaseHandle { /* Dito */ };
class FaceHandle : public BaseHandle { /* Dito */ };

All classes do not have virtual functions or bases.
Derived classes are made only from BaseHandleand do not add any non-static elements, not non-standard dtors.

I want to save Vertex-, Edge-and FaceHandlesin the same vector:

std::vector<BaseHandle*> handles;

But this will not work if I retrieve the object BaseHandleand want dynamic_castthem to the derived object to fail, because the classes are not polymorphic (which may be my explanation, I'm wrong).

How could I get a common vector BaseHandles? I should mention that I cannot change class definitions because they are part of a third-party library.

+4
4

. " , ". :

class MyBaseHandle {
 public:
  virtual ~MyBaseHandle(){}
  virtual Box getBoundingBox() const = 0;
};

class MyEdgeHandle : public MyBaseHandle {
  std::unique_ptr<EdgeHandle> handle_;
 public:
  MyHandle(std::unique_ptr<EdgeHandle> handle) : handle_(std::move(handle)) {}
  Box getBoundingBox() const override;
};

dynamic_cast, . dynamic_cast . virtual , , . , virtual getBoundingBox , :

Box MyEdgeHandle::getBoundingBox() const {

  // Get data from EdgeHandle
  auto v1 = handle_->getVertex1();
  auto v2 = handle_->getVertex2();

  // create box from edge data...

  return box;
} 

+1

,

class BaseHandle 
{
  public:
    virtual ~BaseHandle();

  ...

};

, dynamic_cast RTTI ( RunTime), ,

,


std::vector std::shared_ptr, , new delete , ( , , , ), :

int main()
{
  std::vector<std::shared_ptr<BaseHandle>>      shared_vec;

  shared_vec.push_back(std::make_shared<VertexHandle>());

} // At the end of scope all destructors are called correctly

++ 11, boost::shared_ptr

+6

struct thing
{
    enum Type { vertex, edge, face };
    Type type;
    union
    {
        VertexHandle * vh;
        EdgeHandle * eh;
        FaceHandle * fh;
    };
};

... , ? , , , , , ?

+3

, BaseHandle, BaseHandle (, , dtor, ) , virtual static, dtor , static_cast .

Although, remember that there is no way to find out which of the derived classes, if any, actually existed.

+1
source

All Articles