Why do pure virtual base classes get direct access to static data members while derived instances do
- by Shamster
I've created a simple pair of classes. One is pure virtual with a static data member, and the other is derived from the base, as follows:
#include <iostream>
template <class T>
class Base {
public:
Base (const T _member) {
member = _member;
}
static T member;
virtual void Print () const = 0;
};
template <class T> T Base<T>::member;
template <class T> void Base<T>::Print () const { std::cout << "Base: " << member << std::endl; }
template <class T>
class Derived : public Base<T> {
public:
Derived (const T _member) : Base<T>(_member) { }
virtual void Print () const { std::cout << "Derived: " << this->member << std::endl; }
};
I've found from this relationship that when I need access to the static data member in the base class, I can call it with direct access as if it were a regular, non-static class member. i.e. - the Base::Print() method does not require a this- modifier.
However, the derived class does require the this-member indirect access syntax. I don't understand why this is. Both class methods are accessing the same static data, so why does the derived class need further specification?
A simple call to test it is:
int main () {
Derived<double> dd (7.0);
dd.Print();
return 0;
}
which prints the expected "Derived: 7"