I have a class with a static member. This will be initialized using a private static function of the same class.
#include <iostream>
#include <string>
class A
{
public:
static std::string const s;
private:
static std::string make()
{
return "S";
}
};
std::string const A::s = A::make();
int main()
{
std::cout << A::s << std::endl;
// std::cout << A::make() << std::endl; // <-- Does not work
return 0;
}
My question is: Because of which rule is this allowed? Clearly the commented part does not work, because I am not allowed to access a private function from outside the class. So why is the initialization of the private static member during startup a special case? (And on a side note: what is the intention of this rule? Is it to allow this exact case?)
I am aware of other mechanisms to initialize a static member (like here: Initializing private static members). But in my case the member is const, so as far as I know the only way to set it is via direct initalization at the place of definition.
In Java, private variables are visible to the whole class. They can be accessed from static methods and from other instances of the same class.
Yes, we can have private methods or private static methods in an interface in Java 9.
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
Because the initialization of a static data member is considered part of the characterization of the class even though the static data member is defined at namespace scope (outside the class definition).
From the standard, class.static.data#note-1:
[Note 1: The initializer in the definition of a static data member is in the scope of its class ([basic.scope.class]). — end note]
[Example 1:
class process { static process* run_chain; static process* running; }; process* process::running = get_main(); process* process::run_chain = running;
The definition of the static data member
run_chain
of classprocess
inhabits the global scope; the notationprocess::run_chain
indicates that the memberrun_chain
is a member of classprocess
and in the scope of classprocess
. In the static data member definition, the initializer expression refers to the static data memberrunning
of classprocess
. — end example]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With