1 #include <iostream>
2
3
4 usingnamespace std;
5
6 class A
7 {
8 private:
9 int val;
12 public:
13 explicit A(int x){val = x;}
14 ~A(){}
15 A operator*(A &rhs);
16 const A operator*(const A& rhs);
20 };
21
22 A A::operator*(A &rhs)
23 {
24 cout<<"not constant"<<endl;
25 returnconst_cast<A>(*this * static_cast<const A&>(rhs));//I want to call the constant operator * below.
30 }
31 const A A::operator*(const A &rhs)
32 {
33 cout<<"constant"<<endl;
34 A tmp(10);
35 tmp.val = this->val * rhs.val;
36 return tmp;
37 }
38
39
40 int main()
41 {
42 A obj1(15),obj2(10);
43 A obj3(9);
51 obj3 = (obj1*obj2);
return 0;
}
I have an overloaded * operator one which returns a constant and takes a constant reference while the other has no const. Its a test program and I am wondering how do i use my call to the non constant function to call the function overload. Thanks.
static_cast<const A&>(tmp); is not needed. Returning a refence (or pointer) to a temprory variable is an error. Then you must return a copy of A which you did previously