On Jun 18, 1:32*pm, tech <naumansulai...@googlemail.comwrote:
* * * * * * * *Hi, I want to return a reference to memberobject
provided in class Test, so have
* * * * * * * provided a getter function GetObj() and declared it
const. However i'm getting a
* * * * * * * *compiler error that i need to return reference to const
obj but if i do do this
* * * * * * * i can't call non const member functions eg
GetObj().NonConstFoo()
* * * * * * * How do i get round this problem. I woul thinkthat
GetObj is logically const as
* * * * * * * *it does not change the object.This is on MSVC++ V8.0
* * * * * * * *class Obj
* * * * {
* * * * };
* * * * class Test
* * * * {
* * * * public:
* * * * * * * * Obj& GetObj() const
* * * * * * * * {
* * * * * * * * * * * * return m_obj;
* * * * * * * * }
* * * * private:
* * * * * * * * Obj m_obj;
* * * * };
Hi
const member functions is a kind member functions that you can't
change the state of object through them.
GetObj() is const. so you can't change the state of Test object (here
is m_Obj) via it. on the other hand
it returns the reference to data member. so accord to reference
concept it is ready to change. for example
you can call a non-const member function of class Obj:
class Obj {
void Change() { // ... } // non-const
};
Test t;
t.GetObj().Change();
clearly, this is a contradiction. So before any use Test class
compiler complains.
There are two workarounds:
1. If you intend to change the m_Obj, declare GetObj() as an ordinary
member function.
2. If you intend to return a copy of m_Obj, change the return type to
Obj (return the value of m_Obj)
Good luck
Regards,
Saeed Amrollahi