0
class A {
public:
    A();
    int get();
    void set();
};

protected int A::var;

seems like it would work. However, it "expects an unqualified-id before protected". What's the correct way to do this?

Nathan Ringo
  • 973
  • 2
  • 10
  • 30

3 Answers3

6

In simple words, No it is not possible.

in complex words, It is not possible because the standard allows the keyword and access specifier protected to be used only inside the class definition.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
6

How would the compiler know how much space to allocate for instances of the class? Consider

A foo;
protected int A::var;
A bar;

How would the compiler know to allocate space for var when it allocated foo? The first and second lines could even be in different translation units.

So, no, it's not possible because it doesn't make sense.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

There's no way to do exactly what you want (as others have said), but there are "hacks" around this if you just don't want to reveal protected/private members to users of your class. You can create a PrivateBase and PublicBase class, and then a third class that uses multiple inheritance or composition of the two former classes. Typically, this is done because you want to distribute a header file but you don't want to reveal all your private members.

Here is an example of such. I believe Scott Meyers also has an example in one of his books. It's a lot more work and makes maintenance on your end a lot more complex, so keep that in mind.

Community
  • 1
  • 1
greg
  • 4,843
  • 32
  • 47