typedef vector<int> intvec;
class MyClass
{
intvec m_member;
public:
const intvec& GetVec();
};
const intvec& MyClass::GetVec()
{
return m_member;
}
int main(int argc, char *argv[])
{
MyClass myClassObj;
myClassObj.GetVec().push_back(11); //This doesn't work with const reference
myClassObj.GetVec().push_back(22); //This doesn't work with const reference
for(intvec::const_iterator iter = myClassObj.GetVec().begin(); iter != myClassObj.GetVec().end(); ++iter)
{
cout << *iter << ", " ;
}
cout << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
If the return type of GetVec()
is non const reference then myClassObj.GetVec().push_back(11);
works, but for const reference return this doesn't work (compilation error). I understand that if the GetVec() method itself was const i.e. const intvec& GetVec() const;
, then myClassObj.GetVec().push_back(11);
wouldn't work because that would mean modifying the "this" pointer.
You can overload the function on it's const
qualification:
const intvec& GetVec() const; // Can access, but not modify, a const object
intvec& GetVec(); // Can access or modify a non-const object
Or you could just make the data member public and have exactly the same restrictions. There's little point in accessor functions unless they're used to restrict access or maintain class invariants, which these don't.