0

I have the following classes.

// My baseclass
class Item {
    public:
    virtual const std::string GetItemName() = 0;
};

// My derived class
class Shovel : public Item {
    private:
    static const std::string _ITEM_NAME = "tool_shovel";

    public:
    const std::string GetItemName(){
        return _ITEM_NAME;
    }
}

With this i can access the names of my Item objects like this:

Item* myItem = new Shovel();

myItem.GetItemName(); // Returns "tool_shovel" ofcourse

I would now also like to access the name of an item without having an instance of it like this.

Shovel::GetItemName();

I know it is not possible to implement a virtual static function. but is there any way to implement this in a 'nice' way or is this more a problem in my concept?

Thanks for the help!

Praind
  • 1,551
  • 1
  • 12
  • 25
  • Overloading with static keyword is not allowed: http://stackoverflow.com/questions/5365689/c-overload-static-function-with-non-static-function – LogicStuff Mar 26 '15 at 18:31
  • I know that but my question is if there is another way to implement this or if it's generaly a bad idea to make a property static accessible as well as non-static. – Praind Mar 26 '15 at 18:36

1 Answers1

0

I didn't know it is possible to call a static function directly from an instance, so i solved my problem now with 2 methods. One public static function, so i can get the name of an item at any time. And another private non-static function to let the baseclass get the name of the current item.

Here is the code:

// My baseclass
class Item {
    protected:
    virtual const std::string _GetItemName() = 0;
};

// My derived class
class Shovel : public Item {
    private:
    static const std::string _ITEM_NAME = "tool_shovel";

    protected:
    const std::string _GetItemName(){
        return _ITEM_NAME;
    }

    public:
    static const std::string GetItemName(){
        return _ITEM_NAME;
    }
};

I hope this helps anyone. If you have questions feel free to ask.

Praind
  • 1,551
  • 1
  • 12
  • 25