tamil_innov
tamil_innov

Reputation: 223

C++ how to access base class static members in derived class?

I am new to c++ static varibles. I don't know how to access the static member of base class from the derived class member function.

Example:

#include <iostream>

class base // base class
{
protected:
    static int value;
};

int base::value = 0; // static variable initalization

class derived : public base
{
public:
    get_variable();
};

I know that static variable is a class variable. We can only access it by using class name and it is not binded to object (correct me if I'm wrong). My question is how can I access the static variable in the member functions of the derived class get_varible access the static variable.?

Upvotes: 3

Views: 7171

Answers (3)

user8502334
user8502334

Reputation: 1

You can access the variable from the derived class like this:

int derived::get_variable()
{
     return base::value;
}

You need to use the name of the base class because the variable is static and you're allowed to access it because it is protected.

As explained here and here, the extra checks that don't allow access to protected members of a class from a derived class in certain circumstances don't apply to static members.

Upvotes: 0

Daniel
Daniel

Reputation: 2185

Just use it as it's a member of the derived class.

int derived::get_variable()
{
   return value; 
}

Upvotes: 1

VP.
VP.

Reputation: 16775

You should change private to protected in base class. Your private static variable can be only accessed within base class.

Upvotes: 2

Related Questions