How can I call an overloaded class member function with const qualifier from the nonconst one?

Hi, I got a question here. When I created a class using some sort of member functions, I could hardly distinguish the constness between overloaded ones. For example, I tried to call the const function from the nonconst one, while the compiler did some recursive call and caused the stack overflowed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

using namespace std;

class Test{
    string text="hello,world!";
public:
    const Test &func(ostream &os)const {os<<text; return *this;}
    Test &func(ostream &os){return const_cast<Text &> (func(os));}
    //call the func() with const qualifier, but turn out to be a recursive call
}

int main(){
    Test t1;
    const Test t2;
    t2.func(cout);    //print the string
    cout<<endl;
    t1.func(cout);    //won't yield "hello,world!"
    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

using namespace std;

class Test {
    string text = "hello,world!";
public:
    const Test &func(ostream &os)const { os << text; return *this; }
    Test& func(ostream& os) {
        const Test& t = *this;
        return const_cast<Test&>(t.func(os));
    }
};

int main() {
    Test t1;
    const Test t2;
    t2.func(cout);    //print the string
    cout << endl;
    t1.func(cout);    //won't yield "hello,world!"
    return 0;
}


Although, the correct thing to do would be to just not provide an implementation for a non-const func.
Thanks, it works. Actually, it is weird to add a const then cast it off, you're right, it's much better not to implement it.
Topic archived. No new replies allowed.