Frustrating "redefinition" error



I have a simple header file and a cpp file. In the header I am declaring a class, and in the cpp file, defining it. Here is the header file
(RuntimeException.h)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef EXC_H
#define EXC_H

#include <string>				// provides string
#include <iostream>				// provides ostream
using std::string;				// make string accessible


class RuntimeException {		// generic run-time exception
private:
  string errorMsg;
public:
  RuntimeException(const string& err);
  string getMessage() const;
};

std::ostream& operator<<(std::ostream& out, const RuntimeException& e);
 
#endif


Here is the cpp file (exceptions.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
#include "RuntimeException.h"


RuntimeException::RuntimeException(const string& err) {
 errorMsg = err;
 }
RuntimeException::string getMessage() const {
 return errorMsg;
 }

 std::ostream& operator<<(std::ostream& out, const RuntimeException& e)
{ return out << e.getMessage(); };



When I run "g++ -c exceptions.cpp", I get:



exceptions.cpp:4: error: redefinition of ‘RuntimeException::RuntimeException(const std::string&)’
RuntimeException.h:13: error: ‘RuntimeException::RuntimeException(const std::string&)’ previously defined here
exceptions.cpp:7: error: ‘string’ in class ‘RuntimeException’ does not name a type
exceptions.cpp: In function ‘std::ostream& operator<<(std::ostream&, const RuntimeException&)’:
exceptions.cpp:11: error: redefinition of ‘std::ostream& operator<<(std::ostream&, const RuntimeException&)’
RuntimeException.h:17: error: ‘std::ostream& operator<<(std::ostream&, const RuntimeException&)’ previously defined here



I really cannot understand why the compiler thinks I am redefining when I think I am not.

Please help.




RuntimeException::string getMessage() const {

This is all mixed-up. Try

string RuntimeException::getMessage() const {

instead.
Change RuntimeException::string getMessage() const to string RuntimeException::getMessage() const
Last edited on
Thanks.

After fixing this, I was still getting the same error. It seemed to have gone away after renaming the class to "myRuntimeException". Is there a pre-defined class called RuntimeException?

Thanks anyway, now on to other frustrating problems ! :-(
Not that I know of. I copy/pasted your code with the change I showed you earlier and it compiled error/warning free on MSVS2010.
Last edited on
Not that I know of. I copy/pasted your code with the change I showed you earlier and it compiled error/warning free on MSVS2010.


ok, maybe there was a series of errors that I fixed...will try again after changing the name back. Thanks.
With the fix I detailed above, the two compile without error or warning for me with the command line

g++ -c exceptions.cpp

If I had to guess, you hadn't actually saved the edited code until you renamed the class :)
Last edited on
Topic archived. No new replies allowed.