views:

165

answers:

1

Right now my implementation returns the thing by value. The member m_MyObj itself is not const - it's value changes depending on what the user selects with a Combo Box. I am no C++ guru, but I want to do this right. If I simply stick a & in front of GetChosenSourceSystem in both decl. and impl., I get one sort of compiler error. If I do one but not another - another error. If I do return &m_MyObj;. I will not list the errors here for now, unless there is a strong demand for it. I assume that an experienced C++ coder can tell what is going on here. I could omit constness or reference, but I want to make it tight and learn in the process as well.

Thanks!

// In header file
MyObj GetChosenThingy() const;

// In Implementation file.
MyObj MyDlg::GetChosenThingy() const
{
    return m_MyObj;
}
+8  A: 

The returned object will have to be const, so you cant change it from outside;

// In header file
const MyObj& GetChosenThingy() const;

// In Implementation file.
const MyObj& MyDlg::GetChosenThingy() const
{
    return m_MyObj;
}
Viktor Sehr
You're right...+1
codaddict
Another thing to keep in mind. If, as I assume, m_MyObj is a data member of MyDlg, make sure that the reference isn't kept around any longer that the object that returned it. If you try to access a member of an object that has been deleted, nothing good can happen.
KeithB
Thank you, will do.
Hamish Grubijan
Also, would you please elaborate which const does what?
Hamish Grubijan
Viktor Sehr