Sunday, March 01, 2009

Accessing static members of a class

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.

1 comment:

Nichole said...

One of the things that programmers like to do with numbers and variables is see whether two numbers or variables are equal to each other. C++ provides an operator called the equality operator (==) precisely for this purpose.

Botox Michigan