Search code examples
c++classvariablesscopedatamember

Modifying an object also modifies all other objects of the same class


It's a long time ago since my last c++ project and now I'm stuck in a very simple problem. I create two objects and want to modify only one of them. Now I don't understand why the other object is also modified...

MainClass:

#include "testobject.h"
#include <iostream>

int main() {
    TestObject o1;
    TestObject o2;

    std::cout << "object1 before: " << o1.getI() << std::endl;
    std::cout << "object2 before: " << o2.getI() << std::endl;

    o1.setI(2);

    std::cout << "object1 after: " << o1.getI() << std::endl;
    std::cout << "object2 after: " << o2.getI() << std::endl;

}

TestObjectClass:

#include "testobject.h"

int i;

int TestObject::getI() {
    return i;
}

void TestObject::setI(int j) {
    i = j;
}

The output is:

object1 before: 0
object2 before: 0
object1 after: 2
object2 after: 2

Why is i in object2 also set to 2?


Solution

  • The both objects refer to the common variable

    int i;
    

    declared in the global namespace. So once the variable is changed the class method

    int TestObject::getI() {
        return i;
    }
    

    will return the same value of the variable i for both objects.

    Make the variable a data member of the class.

    For example

    class TestObject
    {
        //...
    private:
        int i;
    };
    

    Pay attention to that the member function getI should be declared with the qualifier const because it does not change the object itself

    class TestObject
    {
    public:
        int getI() const {
            return i;
        }
    //...
    };