开发者

Object with abstract member(without pointers)

I have the following class,

class Simulation {
public:
  btDefaultCollisionConfigu开发者_开发百科ration collisionConfiguration;
  btBroadphaseInterface broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() {
    broadphase = btCollisionDispatcher(&collisionConfiguration);
  }
}

and when I compile I get this error

cannot declare field ‘Simulation::broadphase’ to be of abstract type ‘btBroadphaseInterface’

Now I think I know what I did wrong. If this compiled then the moment I called the constructor the memory allocated would be for a virtual class and wouldn't contain the subclass(btCollisionDispatcher). I know how to solve this with pointers, but I've been hearing from people that you should advoid pointers in C++ and I thought I would give it a try. I've been successful so far but I don't know what to do here.


Yeah, you can only have pointers or references to abstract classes because you can't instantiate an abstract class because, by definition, it has an "incomplete" definition (not to be taken literally). It's just an interface.

If you want to avoid pointers, you can use references, like this:

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  btBroadphaseInterface& broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() : broadphase(someFunctionThatReturnsAbtBroadphaseInterfaceReference()) {

  }
}

Or smart pointers, like this:

// header for shared_ptr
#include <memory>

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  shared_ptr<btBroadphaseInterface> broadphase;
  btSequentialImpulseConstraintSolver solver;
  btDynamicsWorld dynamicsWorld;

  Simulation() : broadphase(someFunctionThatReturnsAbtBroadphaseInterfacePointerOrSmartPointer()) {

  }
}


Since in your implementation of the class you are already fixing the type, why not just store a variable of the actual type to be used?

class Simulation {
public:
  btDefaultCollisionConfiguration collisionConfiguration;
  btCollisionDispatcher broadphase;

  Simulation() : broadphase(&collisionConfiguration) {
  }
};

Note that the code above is correct, but may be prone to error as one member depends for initialization on a different member, be sure not to reorder the declarations in the class.

If, on the other hand, the actual type to be used is not to be hardcoded, then you will need to pass a pointer or reference (and ensure that lifetimes of the different objects is correct).


There is absolutely no problem in using pointers.

At least while you use some libraries you should try to do the things in the way they think of them.

The best way to do what you mean is actually using them.

Don't worry about them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜