Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ compiler error: "return type specification for constructor invalid"

Tags:

c++

Here's my code. When compiling all the files I get this error, I am not sure what I am doing wrong. Please advise.

Molecule.cpp:7:34: error: return type specification for constructor invalid

//Sunny Pathak
//Molecule.cpp    
#include <iostream>
#include "Molecule.h"    
using namespace std;

inline void Molecule::Molecule(){
       int count;
       count = 0;
}//end function

bool Molecule::read(){
    cout << "Enter structure: %c\n" << structure << endl;
    cout << "Enter full name: %c\n" << name << endl;
    cout << "Enter weight   : %f\n" << weight << endl;
}//end function


void Molecule::display() const{
    cout << structure << ' ' << name << ' ' << weight << ' ' << endl;
}//end function
like image 774
Sunny Avatar asked Feb 14 '13 23:02

Sunny


4 Answers

A constructor has no return type:

class Molecule
{
 public:
  Molecule();  // constructor. No return type.
  bool read();
  void display() const;
};

Molecule::Molecule(){
       int count;
       count = 0;
}//end constructor

Also note that count is local to the body of the constructor, and you are not using it for anything.

like image 195
juanchopanza Avatar answered Oct 30 '22 11:10

juanchopanza


You're writing a constructor with a return type. Constructors have no return type. Just change your constructor definition into:

/* void */ Molecule::Molecule()
// ^^^^ Remove this
{
    int count;
    count = 0;
}
like image 42
Andy Prowl Avatar answered Oct 30 '22 09:10

Andy Prowl


Constructor can not have return type.

update:

inline void Molecule::Molecule(){
       ^^^
       int count;
       count = 0;
}//end function

to:

Molecule::Molecule(){
       int count;
       count = 0;
}//end function
like image 2
billz Avatar answered Oct 30 '22 09:10

billz


This same error message can occur when :

  • Class is defined in H file but is missing semicolon
  • Your CPP file includes the H file, and also begins with the definition for the class constructor.

The compiler will then see your class definition as the return type for the constructor method, and throw this error. If that's the case, then the fix is to add the semicolon.

Note : this is not the case in the OP's example, but the error reported (and hence title of this question post) would be the same.

like image 2
Elliot Woods Avatar answered Oct 30 '22 11:10

Elliot Woods