Inheritance between two classes in c++ using the same data members and functions -


i'm new c++ programming , want create 2 classes have exact same data members , functions. possible create 2 inherited classes have same data members/functions instead of making several duplicate methods each class. i'm making c++ game based on zork , want create 2 items, weapons , fruits. both take in name string , value double. create header file below:

    #ifndef item_h_     #define item_h_      #include <map>     #include <string>     #include <iostream>     using namespace std;      class item {     private:         string description;         string longdescription;         float value;      public:         item (string description, float invalue);         item (string description);         string getshortdescription();         string getlongdescription();         float getvalue();         void setvalue(float value);     }; class weapon:: public item{      };      class fruit:: public item {     };       #endif /*item_h_*/ 

how no go creating methods without duplicating them?

do nothing now. both weapon , fruit are items , contain members , methods item does.

sooner or later, you'll want specialize behaviour of child classes , implementation of method in base class won't (if it's sensible have implementation in first place). polymorphism comes in. you'll make method in base class virtual , override in derived class:

class item { public:     virtual void use() = 0;  // pure virtual method };  class weapon : public item { public:     virtual void use() override     {         fire();     } private:     void fire() { /* */ } }; 

now when have reference or pointer base class , call use on it, it'll dispatch corresponding method in derived class.

edit: there's no way around "duplicating" constructors. each class needs @ least 1 if ever instantiated. since declared item (string description, float invalue); need define member of item, too:

item (string description, float invalue)     : description(description) // <-- avoid duplicating names of members in parameter list,     , value(invalue)           // right thing, hurts readability     { /* body empty */ } 

if need call constructor of derived class same parameters, need define constructor , forward arguments constructor of base class:

weapon::weapon(string desc, float val) : item(desc, val) { } 

in c++11, there's shortcut - can inherit constructors , compiler generate these forwarding constructors you:

class weapon : public item {      using item::item; }; 

there's (unfortunately, perhaps) no way specify constructors want inherit. it's or nothing.

hope helps.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -