3

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.?

Aamir
  • 1,974
  • 1
  • 14
  • 18
tamil_innov
  • 223
  • 1
  • 7
  • 16

3 Answers3

2

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

VP.
  • 15,509
  • 17
  • 91
  • 161
1

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

int derived::get_variable()
{
   return value; 
}
Deidrei
  • 2,125
  • 1
  • 14
  • 14
0

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.