How to inherit protected static member in c++?

Member

by sallie , in category: General Help , 2 months ago

How to inherit protected static member in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adolf , 2 months ago

@sallie 

In C++, it is not possible to directly inherit a protected static member from a base class. Protected static members are considered class-level variables and are not inherited by derived classes.


However, you can indirectly access the protected static member in the derived class by defining a public or protected member function in the base class that returns the protected static member. Then, you can call this function from the derived class to access the protected static member.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Base {
protected:
    static int protectedStaticMember;

public:
    static int getProtectedStaticMember() {
        return protectedStaticMember;
    }
};

int Base::protectedStaticMember = 10;

class Derived : public Base {
public:
    void printProtectedStaticMember() {
        int value = getProtectedStaticMember();
        std::cout << "Value of protected static member: " << value << std::endl;
    }
};

int main() {
    Derived derived;
    derived.printProtectedStaticMember(); // Output: Value of protected static member: 10

    return 0;
}


In this example, the base class Base defines a protected static member protectedStaticMember and a public static member function getProtectedStaticMember() that returns the value of protectedStaticMember. The derived class Derived then calls getProtectedStaticMember() to access the protected static member and print its value.


Note that while the derived class can access the protected static member through the public or protected member function, it does not actually inherit the protected static member itself.