Hi guys, I have a problem about const and member function overloading operator.
Well, if I do something like
1 2 3 4 5 6
int c; /c is global
constint &try (int a, int b)
{
c=a*b;
return c;
}
i won't be able to do
try(A,B)=5
becuase, obviously, funciont try returns a CONST int.
BUT
when I overload operator, like =, returning an object reference and declaring the member function as const, I CAN make an assignment. For instance, the member function is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
const Array &Array::operator=(const Array& Ar)
{
if (this==&Ar) cout <<"You cant' initialize an object with itself!" <<endl;
else
{
cout <<"Initialization of object with an object" <<endl;
delete [] this->ptr;
ptr= newint[Ar.size];
size=Ar.size;
for (int i=0; i<size; i++)
{
ptr[i]=Ar.ptr[i];
}
}
return *this;
}
and in the main I do
object1=object2=object3
Why the compiler allow me to do this? I cant' figure it out. Can you help me please?
The const keyword in the context of the OP is that the reference that is returned is const. Meaning you can assign to a non-const object, but the returned reference is a const one. This is why the post above me is correct.
I think you are confusing const return values with const functions. Functions with const return values use const at the beginning in the function (as part of the return type), but const functions (functions that can be called using const instances of an object) need const at the end of the function signature.
1 2 3 4 5
struct Foo
{
void foo() const; //can be called with a const Foo as well as a non-const
void bar(); //can only be called with a non-const Foo
};