Home > Back-end >  How to use the same object instance when creating other objects?
How to use the same object instance when creating other objects?

Time:08-08

I'm new to C and started playing with references, which led me to the following code:

#include <iostream>
#include <unordered_map>

class Wrapper {
private:
    std::unordered_map<std::string, int> map;
public:
    void add(std::string &key, int value) { map[key] = value; }
    int get(std::string &key) { return map[key]; }
};

class Writer {
private:
    Wrapper wrapper;
public:
    explicit Writer(const Wrapper &wrapper) : wrapper(wrapper) 
    { 
        std::cout << "Writer: " << &wrapper << std::endl; 
    }
    void write(std::string key, int value) { wrapper.add(key, value); }
};

class Reader {
private:
    Wrapper wrapper;
public:
    explicit Reader(const Wrapper &wrapper) : wrapper(wrapper) 
    { 
        std::cout << "Reader: " << &wrapper << std::endl; 
    }
    int read(std::string key) { return wrapper.get(key); }
};

My main function:

int main() 
{
    Wrapper wrapper;
    Writer writer(wrapper);
    Reader reader(wrapper);

    writer.write("key", 123);
    std::cout << "Value: " << reader.read("key") << std::endl;
}

I pass a reference to the same instance of the Wrapper class when I create an instance of Writer and Reader. I expected that the value added by the writer should also be available to the reader, since they use the same wrapper instance. However, the read("key") call returns 0 because the key is unknown.

What am I doing wrong and how can I achieve the desired behavior?

CodePudding user response:

member variable must also be declared as reference, in both reader and writer

class Writer {
private:
    Wrapper & wrapper;
}


class Reader {
private:
    Wrapper & wrapper;
}
  •  Tags:  
  • c
  • Related