Reputation: 2063
I come from Java background and I have the following little scenario that doesn't fit my understanding:
template<typename T>
class GeomObject{
public:
T position;
virtual Vec3<T> getPosition() = 0;
}
template<typename T>
class Plane : public GeomObject<T> {
public:
Vec3<T> position;
T range;
Vec3<T> getPosition() { return position; }
T getRange() { return range;}
}
In my main:
vector<GeomObject<float>*> g_objects;
g_objects.push_back(new Plane<float>());
g_objects[0]->getRange(); //ERROR
I cannot access the getRange() method somehow. This was possible in Java but here is not, not even by casting (Sphere)g_objects[0]->getRange(); I would like tho, to keep the vector as a vector of GeomObjects . Is there something I am doing wrong?
Upvotes: 1
Views: 64
Reputation: 16243
The getRange
member function isn't part of the GeomObject
definition, so you cannot call it through a pointer to GeomObject
.
Try adding this in GeomObject
:
virtual T getRange() = 0;
From further comments, it's made clear that getRange
is specific to a Plane
, so it cannot be added as a (pure) virtual member function in GeomObject
.
In that case, you can still access Plane::getRange
, but you'll have to downcast the pointer first. Eg. using dynamic_cast
:
dynamic_cast<Plane<float>*>(g_objects[0])->getRange();
(omitting error checks for brevity).
Having to resort to this, is usually a code smell though. Ie. it's a sign that your design could be improved.
Upvotes: 7