Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing public static members of a base class specified as private

I'm learning C++. The documentation docs.microsoft.com/en-us/cpp/cpp/member-access-control-cpp says:

When you specify a base class as private, it affects only nonstatic members. Public static members are still accessible in the derived classes.

However, the following code slightly adjusted from the example following the previous quote cause error C2247:

'Base::y' not accessible because 'Derived1' uses 'private' to inherit from 'Base'.

I will appreciate any help with this situation.

class Base
{
public:
    int x;             
    static int y;      
};

class Derived1 : private Base
{
};

class Derived2 : public Derived1
{
public:
    int ShowCount();    
};

int Derived2::ShowCount()
{
    int cCount = Base::y;       
    return cCount;
}
like image 720
KarlEL Avatar asked Nov 27 '17 08:11

KarlEL


People also ask

Can a derived class access static members of a base class?

Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

Can derived class access private members of base class in C++?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.

Can a derived class access public members?

A class can always access its own (non-inherited) members. The public accesses the members of a class based on the access specifiers of the class it is accessing. A derived class accesses inherited members based on the access specifier inherited from the parent class.

How is access control established for members and external users in C ++?

Access Control in Derived Classes Two factors control which members of a base class are accessible in a derived class; these same factors control access to the inherited members in the derived class: Whether the derived class declares the base class using the public access specifier.


2 Answers

That documentation is a little misleading.

The correct compiler behaviour is for Base::y and Base::x to both be inaccessible in Derived, if you use that notation to attempt to reach the static member.

But you can reach it via the global namespace (thereby circumventing Derived1) by using another scope resolution operator:

int Derived2::ShowCount()
{
    int cCount = ::Base::y;       
    return cCount;
}

Finally, don't forget to define y somewhere if you want the link stage to be successful.

like image 85
Bathsheba Avatar answered Oct 13 '22 00:10

Bathsheba


Change this:

Base::y;

to this;

::Base::y;
like image 24
gsamaras Avatar answered Oct 13 '22 01:10

gsamaras