Static members of a class are not associated with any one particular instance/object of it. They can even be accessed without any instance. The way to refer to them in your code is as shown below:
[CODE]
class Test
{
private:
static const std::string className;
public:
static const std::string& getClassName()
{
return className;
}
//other members
};
int main()
{
std::cout << Test::getClassName();
}
It is also allowed to be able to access the static members via an instance/object as below: (modifying the above main function and keeping reset the same)
int main()
{
Test testObject;
std::cout << testObject.getClassName();
}
Usually though, it is better to use the previous notation using the scope resolution operator (op '::'). That makes the code more readable in the sense that you know it is a static member and not a non-static one. It speaks for itself.
Showing posts with label scope resolution operator. Show all posts
Showing posts with label scope resolution operator. Show all posts
Sunday, March 01, 2009
Accessing static members of a class
Posted by
abnegator
at
3/01/2009 02:23:00 PM
1 comments
Labels:
C++,
scope resolution operator,
static members
Subscribe to:
Posts (Atom)
