Search code examples
c++inheritancepolymorphismsubclasssuperclass

Accessing protected static members of Superclass by Sub-classes in C++


I have a question. If I have a static member in the superclass, how do I allow all sub-classes of this superclass access and use the static member.

E.g.

/*Superclass*/
class Commands {
   protected:
            static Container database;
};

/*Sub class*/
class Add: public Commands {
   public:
            void add_floating_entry(std::string task_description);  
};

/*This gives me an error. add_floating_task is a method of the Container Class*/
void Add::add_floating_entry(string task_description)
{
   database.add_floating_task(task_description);
}

May I know what is wrong here? Thanks in advance!

EDIT:

The Container class is as follows

class Container {
private:
   vector<Task_Info*> calendar[13][32];
   vector<Task_Info*> task_list;
public:
   void add_floating_task(std::string task_description);
};

The error given is: "Use of undeclared identifier "database"


Solution

  • Define that static member out of the class declaration:

    class Commands {
    protected:
       static Container database; // <-- It's just a declration
    };
    
    Container Commands::database; // <-- You should make a definition
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    The declaration of a static data member in its class definition is not a definition ... The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.

    Your way to make it protected is OK to make it accessible for derived classes.