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
Declaring abstract method static If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
You can't override static methods.
Static members cannot be inherited because they belong to the class declaring them (because they are actually just global variables with some more advanced access), but your derived class can still access them without having to write Base:: (of course they have to be atleast protected ).
You need to declare it in your subclass too.
struct derived : public base {
static const char* componentName;
};
A static member variable means there is a single variable that's shared across all instances of that class. Trying to have one value for the base class and a different value for the derived class doesn't work because they're both sharing the same variable, which (obviously enough) can't simultaneously be set to two different values.
I think the reason is really because the following is true:
&base::componentName == &derived::componentName
they refer to the same object, and initializing an object twice in a
"who laughs last, laughs the best" manner cannot be a good thing.
Cheers.
Vintz
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