A Developer's Diary

Jul 18, 2010

Static Member Functions

A static member function can be accessed using an instance variable or using the class name. It is better to use class name to access a static method as it is more readable and speaks by itself that the method being called is a static member

//File: static_example.h
#include <iostream>
using namespace std;

class StaticExample
{
    public:
        StaticExample();
       ~StaticExample();

        //static member function
        static int StaticMethod();

    private:
        StaticExample(const StaticExample&);
        StaticExample& operator=(const StaticExample&);

        std::string m_str;
};

//File: static_example.cpp
#include "static_example.h"

StaticExample::StaticExample()
{
}

StaticExample::~StaticExample()
{
}

int StaticExample::StaticMethod()
{
    cout << "static method called";
    cout << endl;
    return 0;
}

//File: Main.cpp
#include "static_example.h"

int main()
{
    //using a class name
    StaticExample::StaticMethod();

    //using an instance/object 
    StaticExample obj;
    obj.StaticMethod();

    return 0;
}
Output
$ ./a.exe
static method called
static method called

No comments :

Post a Comment