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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With