overloading

why this code won't work?
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
#include<iostream>

//=============== Complex ============================
class Complex {

	friend Complex operator +(const double& d, const Complex& z) const;					// return const 

private:
	double _r,_i;

public:
	Complex():_r(0),_i(0){}
	Complex(int r,int i):_r(r),_i(i){}

};

//============== Global Functions ===============================
Complex operator +(const double& d, const Complex& z) const {	// he have access for private parameters because of friend declaration
	return Complex(z._r+d,z._i);
}


// =========================== Main Functions ============================================
void foo(){
	Complex z1(1,1),z2,z3;
	z2 = 1 + z1;							// 1
}
// =========================== Main ============================================
int main(){
	foo();

return 0;
}


while this is working good:
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
#include<iostream>

//=============== Complex ============================
class Complex {

	friend Complex operator +(const double& d, const Complex& z) ;					// return non const 

private:
	double _r,_i;

public:
	Complex():_r(0),_i(0){}
	Complex(int r,int i):_r(r),_i(i){}

};

//============== Global Functions ===============================
Complex operator +(const double& d, const Complex& z)  {	// he have access for private parameters because of friend declaration
	return Complex(z._r+d,z._i);
}


// =========================== Main Functions ============================================
void foo(){
	Complex z1(1,1),z2,z3;
	z2 = 1 + z1;							// 1
}
// =========================== Main ============================================
int main(){
	foo();

return 0;
}


when I compile the first code I get:
overloading.cpp:6: error: non-member function ‘Complex operator+(const double&, const Complex&)’ cannot have cv-qualifier
overloading.cpp:20: error: non-member function ‘Complex operator+(const double&, const Complex&)’ cannot have cv-qualifier

const is only for member functions, not global functions.

Your Complex operator +(const double& d, const Complex& z) doesn't need to use const to guarantee that it doesn't change the object it's part of... because it's not part of an object.
ok got it but does it mean that in global function we can't return const ?
what is the reason behind that that global function does not return const?

thanks;
Last edited on
1
2
3
4
5
const int function1(); // this is how you return a const

int function2() const;
// here const says that function2 cannot change contents of the object it's part of
// function2 must be part of a class, and not be a global function 


You can return a const but it doesn't make sense to do so for local variables inside that function.
Last edited on
thanks, It seems that today is not my day !!
Topic archived. No new replies allowed.