views:

90

answers:

3

Just saw this question relating to a segmentation fault issue in a C++ class and program.

My question relates to the class definition. Here it is as it was posted:

class A { 
    int x; 
    int y;

    public: 
    getSum1() const { 
        return getx() + y; 
    } 

    getSum2() const { 
        return y + getx(); 
    }

    getx() const { 
        return x; 
    }     
} 

None of the answers on that question so far made any mention about the return types of the methods. I'd expect them to be defined like

int getSum1() const { ....
int getSum2() const { ....
int getx() const { ....

Do the ints have to be there?

+4  A: 

Yes, in C++ return types must be specified. For a comparison between C and C++, see here.

Michael Goldshteyn
+1  A: 

Yes they do have to be there.

Vinzenz
+2  A: 

Yes, the ints have to be there. The original code sample is not valid (as someone else mentioned the code may have originally been C instead of C++). Firstly, the class declaration needs a terminating semicolon to stand a chance of compiling. g++ reports:

foo.cpp:3: note: (perhaps a semicolon is missing after the definition of ‘A’)

Adding the semicolon we get:

class A { 
  int x; 
  int y;

public: 
  getSum1() const { 
    return getx() + y; 
  } 

  getSum2() const { 
    return y + getx(); 
  }

  getx() const { 
    return x; 
  }     
};

Which still fails. g++ will report the following:

foo.cpp:8: error: ISO C++ forbids declaration of ‘getSum1’ with no type
foo.cpp:12: error: ISO C++ forbids declaration of ‘getSum2’ with no type
foo.cpp:16: error: ISO C++ forbids declaration of ‘getx’ with no type
Richard Cook