3

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

#include <iostream.h>
  class base       // base class
 { 
  protected:
  static int value;
  };

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

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

i know like static variable is a class variable.we can access only by using class name which is not binded with object(correct me if i am wrong).my question is how do i access the static variable in the member functions of the derived class get_varible access the static variable.?

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.

Victor Polevoy
  • 13,984
  • 11
  • 78
  • 145
1

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

int derived::get_variable()
{
   return value; 
}
Deidrei
  • 2,057
  • 1
  • 13
  • 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.