Home » Uncategorized » Static member variables in C++

Static member variables in C++

The static keyword in C++ has many uses in variables and function. Today, I needed a variable which would store the previous value of another variable among executions of a particular function (or method if you prefer since I was using classes). It should not be affected by calls of other objects on the same function. My first thought was the use a static variable, which was a mistake in this context since there is a single instance of a static member variable among different objects of the same class, no matter the scope of the variable (i.e where you declared that particular variable as static). Thankfully, before implementing it, I tested it since C++ is enormous enough to confuse you. My error was obvious after a few lines of code.

// File: Cl.h
#ifndef CL_H
#define CL_H


class Cl
{
    public:
        Cl();
        const static int static_class_variable = 0;
        int member;
        void method(int, bool);
};

#endif
// File: Cl.cpp
#include <iostream>
#include "Cl.h"

Cl::Cl()
{
    member = 1;
}

void Cl::method(int j, bool setme)
{
    static int local_static = 0;
    if (setme) {
        local_static = j;
    }


    std::cout << "static_class_variable is: " << static_class_variable << std::endl;
    std::cout << "local static is: " << local_static << std::endl;
}


int main() {
    Cl obj;


    obj.method(10, false); // static_class_variable is: 0, local static is: 0
    obj.method(10, true); // static_class_variable is: 0, local static is: 10    


    Cl obj2;    


    obj2.method(10, false); // static_class_variable is: 0, local static is: 10
    //obj2.method(10, true);    


    return 0;
}

If anyone wonders how to retain the previous value of a member variable, just use another one.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: