Function with const parameter...

I have a class Class1 with a single member private double a1 and the following two methods:

double Class1::getA1()
{
return a1;
}

Class1 & Class1::method1 (const Class1 & op )
{
double d;
d = op.getA1();
return (*this);
}

compiler keeps telling me : error C2662: 'Class1::getA1' : cannot convert 'this' pointer from 'const Class1' to 'Class1 &'
Conversion loses qualifiers

It works fine with the signature methods1(Class1 & op), but I need it to be const...

Where is the logical error in that? How should my getA1() method look like to be able to retrieve the A1 member for op parameter??

Please advice, appreciated in advance..
Mike
You need a read-only version of getA1()
1
2
3
4
double Class1::getA1() const
{
   return a1;
}

The const after the method header declares the method as read only - which you need for the line d = op.getA1(); since op is a const parameter.
Note that you can have both
double Class1::getA1()
and
double Class1::getA1() const
in the same class - the compiler will use the const one where the object is const, and the non-const otherwise.
Last edited on
thanks Faldrax, that's it, works now...
Topic archived. No new replies allowed.