const overloaded operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
1 #include <iostream>
  2 
  3 
  4 using namespace 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         return const_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.
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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
1 #include <iostream>
  2 
  3 
  4 using namespace 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         return const_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 static_cast<const A&>(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 made the return from the constant overload operator to a constant reference instead and thus did a casting of the tmp object.


warning: reference to local variable âtmpâ returned



I believe this warning must be issued due to casting but is there a better way. Anyone?
Last edited on
You don't need A A::operator*(A &rhs).

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
Topic archived. No new replies allowed.