Copy or reference?

I have a function like this in class Report:
inline const Info& GetInfo() const
    { return *info;}

info is declared in the same Report class as: Info* info

I want to get the info object and call a setter function on that object. The setter function is not const and changes the contents of the info object.

I am trying to do something like this:
Info new_info = my_report->GetInfo();
Is new_info a copy of the object in my_report or the same object?
Can I now call the setter function on new_info object?

If it is a copy, then How do I call setter function on this info object?
It should be a copy, you're returning a value of a pointer and setting that equal to new_info.

If you want to call the setter function on the object that you're getting you need to just return info, not *info;
new_info will be a copy of the Info object in my_report. Using the setter function on the copy should not affect the original object.

You could add another version of GetInfo() that returns a non-const reference to the Info object. You could then make new_info a reference instead and call the setter function to modify the object.
inline Info& GetInfo()
    { return *info;}

Info& new_info = my_report->GetInfo();

If you don't want to give other objects access to the Info object directly you could add a function to Report to do the modifying of the Info object.
Last edited on
Topic archived. No new replies allowed.