Wednesday, June 20, 2007

can't invoke a non-const member function on a const object

we can't invoke a non-const member function on a const object....


Example :

class CTest
{
public:
CTest() { }
~CTest() { }

void Exam() { }
void Exam2() const { }

};


void f( const CTest testObj)
{
testObj.Exam() ; // Will cause an Error , we are invoking a non-const member function in a const object

}






Invoking a non-const member function on a const object.
Possible solutions
Remove the const from the object declaration.
Add const to the member function.


Example
// C2662.cpp
class C
{
public:
void func1();
void func2() const;
} const c;

int main()
{
c.func1(); // C2662
c.func2(); // no error
}

No comments: