Static Member and Inheritance

I have a class with a member m_preferences(a vector containing an association between a word and functions).

In this class, m_preferencesit is not static and, therefore, any instance of the class has its own specific one m_preferences.

class Base{

private:

    Preferences m_preferences;

public:
...

}

Then I created a derived class, where it m_preferencesbecame static, because I wanted every new instance of this class to share the same data for preferences, no matter what happens.

class Derived: public Base{

private:

    static Preferences m_preferences;

public:
...

}

I got a communication error.

Is it possible to do what I want to do (converting a non-static element to static through inheritance)?

If this is not the philosophy of this impossibility? Was this planned?

Thanks,

Yours faithfully,

Ronan

+3
5

Base - Derived - - , .

, Preferences Derived, , - Preferences, , Preferences , Derived.

, - Parent, indentifier m_preferences , Base::m_preferences.

, , , Derived::m_preferences .

. some.cpp, :

Preferences Derived::m_preferences;
+6

, , , Preferences. ?

class Base
{
  virtual ~Base();
  virtual Preferences& MyPreferences() =0;
};

class DerivedA: public Base
{
public:
  virtual ~DerivedA();
  virtual Preferences& MyPreferences() { return m_preferences; }

private:
  Preferences m_preferences;
};

class DerivedB: public Base
{
public:
  virtual ~DerivedB();
  virtual Preferences& MyPreferences() { return preferences; }

private:
  static Preferences preferences;
};

Preferences DerivedB::preferences;

"", , . , "" , , - , , .

+4

: .

: Base . Derived "is-a" (Derived - , ), Base.

, (?):

class NotDerivedAnymore
{

private:

    static Base m_base;

public:
...

}
+4

, , , .

+1

is-a.

, Base - , Preferences, , Derived - Base.

, Base Derived ,

I believe this got the result you want well

class TrueBase{ 
    // Put data and functionality here that really is common for both types.
  private:

    virtual Preferences& get_preferences() = 0;
};

class Base : public TrueBase{
  private:

    virtual Preferences& get_preferences()
    {
        return m_preferences;
    }

    Preferences m_preferences;
};


class Derived: public TrueBase{  
  private:

    virtual Preferences& get_preferences()
    {
        return m_preferences;
    }

    static Preferences m_preferences;   
};
+1
source

Source: https://habr.com/ru/post/1708975/


All Articles