mkmostafa
mkmostafa

Reputation: 3171

Static member variables with same name in base and derived classes

class Base {
   static std::vector<std::string> filter;

   virtual bool check() {
      if(std::find(filter....))
   }
}

class Derived : public Base {
   static std::vector<std::string> filter;

   bool check() override {
      if(std::find(filter....))
   }
}

Assume that both static variables are defined in their respective translational units.

I have a vector of static strings that carries the same name in the base and derived class because they are intended to carry the same type of info just with different values for each class. I know name hiding for functions that are non virtual is not a good idea. Does the same apply to the static member variables? if so what are the alternatives?

Upvotes: 2

Views: 1340

Answers (1)

Caleth
Caleth

Reputation: 62684

Yes, all the same reasons to avoid shadowing non-virtual functions apply to (vacuously non-virtual) members;

I'm going to assume that the override of check() in Derived is textually identical to that of Base.

You can instead use a virtual method with static locals

class Base 
{
    // ...

    virtual /*const?*/ std::vector<std::string> & filter() 
    {
        static std::vector<std::string> value = ...
        return value;
    }
    bool check() // final
    {
        if(std::find(filter()...))
    }
}

class Derived : public Base
{
    /*const?*/ std::vector<std::string> & filter() // override
    {
        static std::vector<std::string> otherValues = ...
        return otherValues;
    }
}

Upvotes: 1

Related Questions