Search code examples
c++inheritancestatic-initialization

cannot override static initialization in derived class


i'm trying to provide different static initializations for classes in a hierarchy, but when i tried with this code:

#include <iostream>

using namespace std;

struct base {
static const char* componentName;
};
const char* base::componentName = "base";

struct derived : public base {};

const char* derived::componentName = "derived";

int main() {

cout << base::componentName << endl;
cout << derived::componentName << endl;
}

I ended up with this build error:

test.cpp:15: error: ISO C++ does not permit ‘base::componentName’ to be defined as ‘derived::componentName’
test.cpp:15: error: redefinition of ‘const char* base::componentName’
test.cpp:11: error: ‘const char* base::componentName’ previously defined here

It seems that static initializations cannot be overriden on the derived classes? If this does not work i might always define the componentName to be a static function that returns a const char*, the only problem with that i was sort of hoping to do initializations for partial specializations, and there does not seem to be any way that i know of to redefine just a single function in a partial specialization, without copying all the other code that will remain mostly the same


Solution

  • You need to declare it in your subclass too.

    struct derived : public base {
        static const char* componentName;
    };