Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to modify the same variable in different classes and modify it?

I have many function definitions which I have placed in different cpp files with function declarations in their respective .h files.

I have a set of a variables which I have placed in a .h file. These variables need to modified by different functions. I am using static to keep the changes from each function, but I heard it is a bad coding practice. How else to do it ? For eg –

variables.h

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class variable{
static int x;
static int y;
};

function1.h

class function(){
public:
void function1();
}

similar for function 2

function 1.cpp

void function1(){
// does something with x and y (used as (variable::x=2;variable::y=3)
}

function2.cpp

void function2(){
// does something with x and y (used as variable::x+=2;variable::y+=2)
}

main.cpp

int variable::x;
int variable::y;
int main(){

obj.function1(); (obj is object of function1 class)
obj2.function2(); (obj2 is object of function2 class)

cout << variable::x << variable::y << endl;
}

I was was using different objects in different cpp files but changes in one function were not reflecting in other. How it use it please help?

>Solution :

You can simply move these variables into another class:

struct Shared {
    int x;
    int y;
};

Now you can pass an instance to this class as parameter to your function, this is called dependency injection:

void foo(Shared& shared) {
    shared.x = 4;
    shared.y = 2;
}

This is better because you don’t have any global state anymore. You could use the function multiple times independent from each other by referencing a different instance of the Shared class.

It is very common to take this a step further by "injecting" the instance in the constructor of that class. This is helpful if the instance of that class should always reference the same instance:

struct Foo {
    Shared& m_shared;

    Foo(Shared& shared)
        : m_shared(shared)
    {

    }

    void foo() {
        m_shared.x = 4;
        m_shared.y = 2;
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading