Home > Software engineering >  All instances of a class share the same values
All instances of a class share the same values

Time:05-09

I've got a class called Data, whenever I declare a new instance of this class and change something in it, it changes all instances of that class. I'm not sure how to fix this, or why it is even happening.

(Note, I've stripped back a lot of what was in my data class, but this example still produces the error)

Data.h

#include <chrono>

volatile class Data{
    public:
        volatile struct Ts{
            volatile int64_t unixTimestamp;
        };

        int ReturnTimestamp() volatile;
        void SetTimestamp(int) volatile;
};

Data.cpp

#include "data.h"
#include <ctime>

volatile Data::Ts data;


int Data::ReturnTimestamp() volatile{
    return data.unixTimestamp;
}

void Data::SetTimestamp(int timestamp) volatile{
    data.unixTimestamp = timestamp;
}

In main I run

int main() {
    Data d1;
    Data d2;
    Data d3;

    d1.SetTimestamp(1);
    d2.SetTimestamp(2);
    d3.SetTimestamp(3);

    printf("%i %i %i\n", d1.ReturnTimestamp(), d2.ReturnTimestamp(), d3.ReturnTimestamp());

    return 0;
}

The output is

3 3 3

I want the output to be

1 2 3

Why is it not "1 2 3" ?

CodePudding user response:

data is not defined in the class, so you create a global variable. Create a member variable.

class Data{
    public:
        struct Ts{
            volatile int64_t unixTimestamp;
        } data;

        int ReturnTimestamp() volatile;
        void SetTimestamp(int) volatile;
};

instead of volatile Data::Ts data;

  • Related