c++ - How to cast pointer to base type conditionally given a pointer to derived type -
i have 2 derived classes, triangle
, sphere
, base of operations class shape
.
i have situation stored base of operations class pointer, shape*
in class a
, , have 2 overloaded fellow member functions of class a
each derived type, dosomething(sphere* sp)
, dosomething(triangle* tr)
.
class shape { public: shape() {}; virtual ~shape() = 0; }; class triangle : public shape { public: triangle(); }; class sphere : public shape { public: sphere(); }; class { private: shape* shape; void dosomething(triangle* tr); void dosomething(sphere* sp); public: a(); ~a(); };
however, when seek run code passing pointer of type shape*
dosomething
function, next error:
candidate function not viable: cannot convert base of operations class pointer 'value_type' (aka 'shape *') derived class pointer 'const triangle *' 1st argument void a::dosomething(triangle* tr) {
and same message sphere
. i'm sure although pointer of type shape *
, points 1 of derived objects.
so, how resolve issue preferably without modifying triangle
, sphere
classes , modifying a
?
there's no way in c++. way dynamic dispatch phone call virtual method:
shape->dosomething();
where maybe triangle::dosomething
, sphere::dosomething
different implementations of virtual shape::dosomething
.
so either need alter code construction it's shape
controls calling. or... can have massive branch seek each 1 in turn:
void dosomething() { if (triangle* t = dynamic_cast<triangle*>(shape)) { dosomething(t); } else if (sphere* s = dynamic_cast<sphere*>(shape)) { dosomething(s); } // etc. }
i recommend not doing though. in additional beingness awful read, it's slow , unmaintainable.
c++ pointers casting
No comments:
Post a Comment