Reputation: 223
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
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
Reputation: 2185
Just use it as it's a member of the derived class.
int derived::get_variable()
{
return value;
}
Upvotes: 1
Reputation: 16775
You should change private
to protected
in base class.
Your private static
variable can be only accessed within base
class.
Upvotes: 2