stonny posted:
But when you call a function, how can you indicate the function you call
is const or not?
It's all about the "this" pointer.
If you have a class with a member function as follows:
class MyClass {
public:
int i;
void Func() { i = 5; }
};
Then it operates under-the-hood as if you wrote it like:
struct MyClass {
int i;
};
void Func(MyClass *const this) { this->i = 5; }
As you can see in the line immediately above, the "this" pointer is a
"pointer to non-const". If we expand the example to the following:
class MyClass {
public:
int i;
void Func() { i = 5; }
void Func() const {}
};
Then again, we can say it operates like:
struct MyClass {
int i;
};
void Func(MyClass *const this) { this->i = 5; }
void Func(MyClass const *const this) {}
We can see that we have function overloading. The function called depends
on whether "this" is a "pointer to const" or "pointer to non-const".
The non-const function is called if you invoke the function on:
(1) A non-const object.
(2) A reference to non-const.
(3) A pointer to non-const.
The const function is called if you invoke the function on:
(1) A const object.
(2) A reference to const.
(3) A pointer to const.
To answer your question: If you have a non-const object, and wish to invoke
a const method upon it, then choose either of:
const_cast<MyClass const &>(obj).Func();
Or:
MyClass const &cr = obj;
cr.Func();
--
Frederick Gotham