简体   繁体   中英

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?

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 .

Static members and class hierarchy don't interact. Polymorphism is about more behavioral forms. However you cant declare again and again static member in class hierarchy. It should be declared once and can be used in throughout the hierarchy of polymorphism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM