2

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?

pax
  • 23
  • 5
  • `wrapper(wrapper)` is calling the [_copy constructor_](https://stackoverflow.com/questions/2168201/what-is-a-copy-constructor-in-c). The default implementation of a copy constructor will make a _copy_. – Drew Dormann Aug 08 '22 at 13:58
  • 3
    You pass a reference but `wrapper` is not a reference in your `Reader` and `Writer` classes. Make it so and it should work. – john Aug 08 '22 at 14:01

1 Answers1

7

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

class Writer {
private:
    Wrapper & wrapper;
}


class Reader {
private:
    Wrapper & wrapper;
}
Marc Stroebel
  • 2,295
  • 1
  • 12
  • 21