5

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?

Andreas
  • 7,470
  • 10
  • 51
  • 73
  • This code will compile, but I don't know if it will work for you, because you haven't explained how would you use it. – Dialecticus Sep 25 '13 at 10:51
  • @Dialecticus I'd instantiate two CocaColaCompanies, expect them both to have myCocaCola.company_name "Coca Cola" and the string "Coca Cola" to lie in memory only at one place. – Andreas Sep 25 '13 at 10:54
  • Why do you think this isn't working? Which compiler are you using? Have you looked in the map file to see where the strings are? The way I understand it, you will have a single "Coca Cola" static char array (in memory), which on initialisation will be passed to the std::string constructor (in memory), so at a minimum you will have the same string in memory twice. – Neil Sep 25 '13 at 10:56
  • this is a good lecture http://stackoverflow.com/questions/11732422/is-polymorphism-possible-without-inheritance – user2485710 Sep 25 '13 at 10:58
  • Your classes are too specific. CocaCola and IBM should be instances of the Company class. Maybe you could derive TechCompany and DrinkCompany classes (IF they behave differently somehow). But specific examples of companies should not be hardset in your design. – Neil Kirk Sep 25 '13 at 11:14
  • @NeilKirk Yes, the class names were poorly chosen for this example, as Sebastian has pointed out. – Andreas Sep 25 '13 at 11:20

2 Answers2

12

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.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
1

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.

Kashif Junaid
  • 21
  • 1
  • 5