I am creating a text editor and I want to use the TextContent class object in two other classes: Editor and InputManager. The problem occurs when changing the buffer in InputManager - the buffer in Editor does not change despite passing by reference TextContent to both classes.
I discovered that the cause is the different address of the buffer in these classes, and the change occurs after calling the constructors.
Code:
Editor::Editor(
sf::RenderWindow &window,
TextContent &content) : textContent(content)
{
std::cout << "Buffer in Editor constructor" << std::endl;
std::cout << &content.buffer << std::endl;
}
InputManager::InputManager(TextContent &content)
:textContent(content)
{
std::cout << "Buffer in InputManager constructor" << std::endl;
std::cout << &textContent.buffer << std::endl;
}
TextContent::TextContent(std::string &filepath)
{
std::ifstream fileStream;
fileStream.open(filepath, std::ios::in);
if(!fileStream)
{
std::cout << "No such file" << std::endl;
}
else
{
std::ostringstream sstr;
sstr << fileStream.rdbuf();
buffer += sstr.str();
}
fileStream.close();
std::cout << "Buffer in TextContent constructor" << std::endl;
std::cout<< &buffer << std::endl;
}
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "TestEditor");
std::string path = "./samples/empty.txt";
TextContent content(path);
Editor editor(window, content);
InputManager in_manager(content);
std::cout << "After init in TextContent:" << std::endl;
std::cout << &content.buffer << std::endl;
std::cout << "After init in Editor:" << std::endl;
std::cout << &(editor.textContent.buffer) << std::endl;
std::cout << "After init in InputManager:" << std::endl;
std::cout << &(in_manager.textContent.buffer) << std::endl;
Output:
Buffer in TextContent constructor
0x7ffe334926a0
Buffer in Editor constructor
0x7ffe334926a0
Buffer in InputManager constructor
0x7ffe334926a0
After init in TextContent:
0x7ffe334926a0
After init in Editor:
0x7ffe33492ae0
After init in InputManager:
0x7ffe334926c0
I am beginner in C++ and have no idea why immediately after executing the constructor address of buffer changes.
Could you find the reason please?