> > int main()
{
foo a(42);
// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();
// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<const foo>(a).print();
Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.
Here's the original code again:
#include <iostream>
using namespace std;
class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}
private:
int data;
};
int main()
{
foo a(42);
// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();
// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<const foo>(a).print();
return 0;
}
OK, let me take a stab again at articulating what I'm after. There are two
member functions in class foo that I care about
: print() and print() const.
If I had a const foo, I would be restricted to calling only print() const.
However, I don't have a const foo (it's the whole point of the problem;
please don't change it to const or you'll be answering a question different
than what I asked, and one that I know the answer too!). Therefore, it is
*semantically* valid for me to call either print() or print() const. This
can be verified by removing the non-const print(). In that case, the
non-const foo object will correctly invoke print() cont.
My question is nothing more than trying to verify that, other than with a
cast to const foo, it is not *syntactically* possible for me to call print()
const (even though it is *semantically* legal, as detailed above). In other
words, I can't do this:
a.print() cost;
Hmmm, it just occurred to me that there may be a way with using a
pointer-to-member, but that would be somewhat ugly too. I think I may have
exhausted the possibilities, but I'm merely throwing this out to those more
experienced than I for confirmation...