c++ - Vector of inherited classes -
i keep looking around fruitlessly solution this,
i have number of classes inherit 1 base class:
#ifndef navalvesselclass #define navalvesselclass #include <iostream> #include <string> class navalvessel { public: std::string name_; std::string type_; std::string operatingcountry_; std::string built_; std::string servicedate_; bool active_; double length_; double displacement_; double beam_; double draft_; double speed_; double range_; private: }; #endif
and then, instance class inherits it:
#ifndef destroyerclass #define destroyerclass #include "surfacecombatant.h" #include <string> class destroyer: public surfacecombatant { public: enum class armamentprimary { antiair, missile }; enum class armamentsecondary { torpedos, missile, antiair, antiground }; armamentprimary primaryarmament; armamentsecondary secondaryarmament; private: }; #endif
now, when want store these objects in vector i'm creating vector follows
std::vector<navalvessel *> shipfleet
using that, can store both, destroyers , other ships in vector pointers, once try , retrieve them again, of course of type 'navalvessel' , cannot access of derived classes variables? e.g. primary weapon, can access base class attributes.
thanks.
your design flawed , won't able without enabling rtti , using dynamic_cast
. useless design remain bad or getting worse.
i suggest reading on oop basics not understand implication of base classes , polymorphism.
the idea of base class provide common set of methods results in different values depending upon implementation of concrete type.
in scenario base class should provide member obtain list of possible weapons , every concrete implementation return set of weapons. ships without weapons return empty list, etc.
but again. have deep flaws in understanding of abstract classes in c++. absolutely necessary provide @ least virtual destructor in base class.
Comments
Post a Comment