c++ - PostActive visibility of class methods -
i have here abstract base class called base_class
defined follows:
class base_class { public: virtual ~base_class() = 0 {} virtual size_t area() const = 0; protected: base_class() {} };
one derived class it:
template <typename t> class : public base_class { public: a(); ~a(); size_t area() const; void display(); (...) etc code };
and class still derived it:
template <typename t> class b : public base_class { public: b(); ~b(); size_t area() const; void set(); (...) etc code };
than have instantiation , function call:
base_class *p = new a<int>; p->display(); delete p; p = new b<float>; p->set(); (...) code
as might have observed, pointer p
won't "see" display
, set
methods.
the question is: when using pointers of type base_class
, there chance of letting derived object call derived methods defined in class points to? being able access display , set methods without having make them virtual in base class.
otherwise have make 2 virtual functions in base_class
, display
, set
, , that's inconvenient, because a
doesn't have inherit set
method, , b
display
method.
you can use dynamic_cast
downcast base class derived class, if not determine runtime type of object.
base_class *p = new a<int>; if (a<int> *pa = dynamic_cast<a<int> *>(p)) pa->display(); delete p; p = new b<float>; if (b<float> *pb = dynamic_cast<b<float> *>(p)) pb->set();
if type of object confirmed @ compile time, static_cast
can cast too, beware: telling compiler know fact being pointed of type. if wrong, cast cannot inform of problem (as dynamic_cast
, return null pointer if cast failed, or throw std::bad_cast
reference cast failure) and, @ best, spurious run-time errors and/or program crashes.
anyway, best practice should rearrange inheritance relationship, try use virtual function, avoid downcasts.
Comments
Post a Comment