<p>Is there anyway to have a sort of virtual static member in C++?</p>

<p>For example:</p>

<pre><code>class BaseClass {
    public:
        BaseClass(const string&amp; name) : _name(name) {}
        string GetName() const { return _name; }
        virtual void UseClass() = 0;
    private:
        const string _name;
};


class DerivedClass : public BaseClass {
    public:
        DerivedClass() : BaseClass("DerivedClass") {}
        virtual void UseClass() { /* do something */ }
};
</code></pre>

<p>I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?</p>

<pre><code>class BaseClass {
    public:
        BaseClass() {}
        virtual string GetName() const = 0;
        virtual void UseClass() = 0;
};


class DerivedClass : public BaseClass {
    public:
        DerivedClass() {}
        virtual string GetName() const { return _name; }
        virtual void UseClass() { /* do something */ }
    private:
        static const string _name;
};

string DerivedClass::_name = "DerivedClass";
</code></pre>

<p>This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.</p>

<p>Any idea?</p>

[{'answer_id': 34591, 'author': 'Hershi', 'author_id': 1596, 'author_profile': 'https://Stackoverflow.com/users/1596', 'pm_score': 2, 'selected': False, 'text': '<p>It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.</p>\n\n<p>If you insist on having the "shared" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.</p>\n\n<p>In general, the example doesn\'t show a need for "virtual static" members, because for purposes like these you don\'t actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each "sub-type" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the "Policy" pattern).</p>\n\n<p>To conclude - for the purpose of the original example, there is no need for such "virtual static" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.</p>\n\n<p>Example of what I described above:</p>\n\n<pre><code>class BaseClass {\n    public:\n        BaseClass(const Descriptor&amp; desc) : _desc(desc) {}\n        string GetName() const { return _desc.name; }\n        int GetId() const { return _desc.Id; }\n        X GetX() connst { return _desc.X; }\n        virtual void UseClass() = 0;\n    private:\n        const Descriptor _desc;\n};\n\n\nclass DerivedClass : public BaseClass {\n    public:\n        DerivedClass() : BaseClass(Descriptor("abc", 1,...)) {}\n        virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n    public:\n        DerivedClass() : BaseClass("Wowzer", 843,...) {}\n        virtual void UseClass() { /* do something */ }\n};\n</code></pre>\n\n<p>I\'d like to elaborate on this solution, and maybe give a solution to the de-initialization problem:</p>\n\n<p>With a small change, you can implement the design described above without necessarily create a new instance of the "descriptor" for each instance of a derived class.</p>\n\n<p>You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:</p>\n\n<pre><code>enum InstanceType {\n    Yellow,\n    Big,\n    BananaHammoc\n}\n\nclass DescriptorsMap{\n    public:\n        static Descriptor* GetDescriptor(InstanceType type) {\n            if ( _instance.Get() == null) {\n                _instance.reset(new DescriptorsMap());\n            }\n            return _instance.Get()-&gt; _descriptors[type];\n        }\n    private:\n        DescriptorsMap() {\n            descriptors[Yellow] = new Descriptor("Yellow", 42, ...);\n            descriptors[Big] = new Descriptor("InJapan", 17, ...)\n            ...\n        }\n\n        ~DescriptorsMap() {\n            /*Delete all the descriptors from the map*/\n        }\n\n        static autoptr&lt;DescriptorsMap&gt; _instance;\n        map&lt;InstanceType, Descriptor*&gt; _descriptors;\n}\n</code></pre>\n\n<p>Now we can do this:</p>\n\n<pre><code>class DerivedClass : public BaseClass {\n    public:\n        DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}\n        virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n    public:\n        DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}\n        virtual void UseClass() { /* do something */ }\n};\n</code></pre>\n\n<p>At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.</p>\n\n<p>So now we have a single instance of each descriptor that is also being deleted at the end of execution.</p>\n\n<p>Note that if the only purpose of the derived class is to supply the relevant "descriptor" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time.</p>\n'}, {'answer_id': 34701, 'author': 'Pat Notz', 'author_id': 825, 'author_profile': 'https://Stackoverflow.com/users/825', 'pm_score': 1, 'selected': False, 'text': '<p>@Hershi: the problem with that approach is that each instance of each derived class has a copy of the data, which may be expensive in some way.</p>\n<p>Perhaps you could try something like this (I\'m spit-balling without a compiling example, but the idea should be clear).</p>\n<pre><code>\n#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nstruct DerivedData\n{\n  DerivedData(const string & word, const int number) :\n    my_word(word), my_number(number) {}\n  const string my_word;\n  const int my_number;\n};\n\nclass Base {\npublic:\n  Base() : m_data(0) {}\n  string getWord() const { return m_data->my_word; }\n  int getNumber() const { return m_data->my_number; }\nprotected:\n  DerivedData * m_data;\n};\n\n\nclass Derived : public Base {\npublic:\n  Derived() : Base() {\n    if(Derived::s_data == 0) {\n      Derived::s_data = new DerivedData("abc", 1);\n    }\n    m_data = s_data;\n  }\nprivate:\n  static DerivedData * s_data;\n};\n\n\nDerivedData * Derived::s_data = 0; \n\nint main()\n{\n  Base * p_b = new Derived();\n  cout getWord() &lt;&lt; endl;\n}\n\n</code></pre>\n<p>Regarding the follow-up question on deleting the static object: the only solution that comes to mind is to use a smart pointer, something like the <a href="https://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm" rel="nofollow noreferrer">Boost shared pointer</a>.</p>\n'}, {'answer_id': 34857, 'author': 'Misha M', 'author_id': 3467, 'author_profile': 'https://Stackoverflow.com/users/3467', 'pm_score': 1, 'selected': False, 'text': '<p>I agree with Hershi\'s suggestion to use a template as the "base class".  From what you\'re describing, it sounds more like a use for templates rather then subclassing.</p>\n\n<p>You could create a template as follows ( have not tried to compile this ):</p>\n\n<pre>\n<code>\ntemplate &lt;typename T&gt;\nclass Object\n{\npublic:\n\n  Object( const T& newObject ) : yourObject(newObject) {} ;\n  T GetObject() const { return yourObject } ;\n  void SetObject( const T& newObject ) { yourObject = newObject } ;\n\nprotected:\n\n  const T yourObject ;\n} ;\n\nclass SomeClassOne\n{\npublic:\n\n  SomeClassOne( const std::vector& someData )\n  {\n    yourData.SetObject( someData ) ;\n  }\n\nprivate:\n\n  Object&lt;std::vector&lt;int&gt;&gt; yourData ;\n} ;\n</code>\n</pre>\n\n<p>This will let you use the template class methods to modify the data as needed from within your custom classes that use the data and share the various aspects of the template class.</p>\n\n<p>If you\'re intent on using inheritance, then you might have to resort to the "joys" of using a void* pointer in your BaseClass and dealing with casting, etc.</p>\n\n<p>However, based on your explanation, it seems like you need templates and not inheritance.</p>\n'}, {'answer_id': 35201, 'author': 'Jeremy', 'author_id': 3657, 'author_profile': 'https://Stackoverflow.com/users/3657', 'pm_score': 4, 'selected': True, 'text': '<p>Here is one solution:  </p>\n\n<pre><code>struct BaseData\n{\n  const string my_word;\n  const int my_number;\n};\n\nclass Base\n{\npublic:\n    Base(const BaseData* apBaseData)\n    {\n        mpBaseData = apBaseData;\n    }\n    const string getMyWord()\n    {\n        return mpBaseData-&gt;my_word;\n    }\n    int getMyNumber()\n    {\n        return mpBaseData-&gt;my_number;\n    }\nprivate:\n    const BaseData* mpBaseData;\n};\n\nclass Derived : public Base\n{\npublic:\n    Derived() : Base(&amp;sBaseData)\n    {\n    }\nprivate:\n    static BaseData sBaseData;\n}\n\nBaseData Derived::BaseData = { "Foo", 42 };\n</code></pre>\n'}, {'answer_id': 895651, 'author': 'no-op', 'author_id': 110250, 'author_profile': 'https://Stackoverflow.com/users/110250', 'pm_score': 0, 'selected': False, 'text': "<p>It sounds as if you're trying to avoid having to duplicate the code at the leaf classes, so why not just derive an intermediate base class from the base class. this intermediate class can hold the static data, and have all your leaf classes derive from the intermediate base class. This presupposes that one static piece of data held over all the derived classes is desired, which seems so from your example.</p>\n"}]
['https://Stackoverflow.com/questions/34506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3373/']