Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a static member variable behave with polymorphism in C++?

I want to store static strings in subclasses so that they are not duplicated in memory. Can it be done like this? I want to be able to instantiate two IBMs but only put the string "IBM" once in memory.

class Company {
    static const std::string company_name;
}
class CocaColaCompany : public Company {
    static const std::string company_name = "Coca Cola";
}
class IBM : public Company {
    static const std::string company_name = "IBM";
}

Or is there a problem with using static members with a polymorphic base class?

like image 296
Andreas Avatar asked Dec 20 '22 23:12

Andreas


1 Answers

Static members and class hierarchies don't interact. Polymorphism is about individual instances.

If you want a company name that is specific to a subclass and fixed there, you should make company_name a virtual getter in the base class and override it in the derived class to return the fixed string.

That said, your little example class hierarchy is worrying, because it mixes levels of abstraction. Neither CocaColaCompany nor IBM are refinements of Company; they're specific companies and thus should be instances. (This is a typical way in which the "is a" rule can lead you astray.) On the other hand, CocaColaSubsidiary could be a subclass of Company.

like image 158
Sebastian Redl Avatar answered Dec 22 '22 14:12

Sebastian Redl