Trygve Flathen
Trygve Flathen

Reputation: 696

gcc compiling error, object initialization interpreted as function pointer?

The following code:

class Angle {
protected:
   double rad;
   Angle(double r) : rad(r){}
};

class Radian : public Angle {
public:
   Radian(double rad) : Angle(rad){}
};

class Latitude : public Angle {
public:
   Latitude(const Angle&a) : Angle(a){}
   Latitude operator-(const Latitude &other){
      return Latitude(Radian(rad-other.rad));
   }
};

int main(){
   double d = 0.7;
   Latitude lat1(Radian(0.8));
   Latitude lat2(Radian(d*1));
   Latitude lat3(Radian(d));
   Latitude diff2 = lat1 - lat2;
   Latitude diff3 = lat1 - lat3;
   return 0;
}

gives compiler error:

$ g++ bug.cpp
bug.cpp: In function ‘int main()’:
bug.cpp:26:26: error: no match for ‘operator-’ (operand types are ‘Latitude’ and ‘Latitude(Radian)’)
    Latitude diff3 = lat1 - lat3;
                          ^
bug.cpp:26:26: note: candidate is:
bug.cpp:15:13: note: Latitude Latitude::operator-(const Latitude&)
    Latitude operator-(const Latitude&l){
             ^
bug.cpp:15:13: note:   no known conversion for argument 1 from ‘Latitude(Radian)’ to ‘const Latitude&’

If I try to do lat3 - lat3 it will give this error, indicating that it interprets lat3 as a function pointer:

error: ISO C++ forbids using pointer to a function in subtraction [-fpermissive]
lat3 - lat3;
       ^

lat2 - lat2 is ok.

So what is going on here? Why is lat2 and lat3 interpreted as different types? What exactly is meant by Latitude(Radian) in the error message?

Compiler output is from gcc 4.9.1, similar results are obtained with gcc versions 4.1 to 4.9. Platform is 64bit RHEL6.

Upvotes: 1

Views: 80

Answers (1)

Klaus
Klaus

Reputation: 25633

change your line to:

Latitude lat3((Radian(d)));

The problem you run into is known as

http://en.wikipedia.org/wiki/Most_vexing_parse

Upvotes: 2

Related Questions