简体   繁体   中英

C++ - Do derived classes inherit static members of the base class?

I've got a base class GameObject that has a member

static Cell **grid;

I've also got a derived class Character which is the base class for another class Player. So my question is: will all objects of GameObject, Character, and Player classes have access to that same grid?

A Player is a Character , which is a GameObject . So yes, they all have access to the static grid .

...Subject to access protection of course (as pointed out by Sam). So you need to declare grid within a public or protected region for this to be true, and furthermore, you would need to declare the inheritance using protected or public modes:

class GameObject
   {
protected:
   static Cell **grid;
   };

class Character : protected GameObject
   {
   };

The rules for whether the static class members of a base class are available to the immediately derived class, the most derived class, or any other class in between, in the class hierarchy depends on:

  • whether the static class member is public, protected, or private.

  • and, in the inheritance chain, whether each class inherits the base class as a public class, protected class, or a private class.

So the answer to your question is: depends. Depends on these factors.

I believe that unless you explicitly use the protected modifier, this property would be considered private. In your example, you didn't prefix it with either protected or public , so it would be considered private and hence not accessible in the derived classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM