K. Shores
K. Shores

Reputation: 1005

Define an error class for C++

I've been trying to define an error class in C++. I have three files; main.cpp, my_class.h, my_class.cpp. If I tried to compile with the below code, all, of course, in three separate files, I would get a multiple definition error of my_exception.

Please note, if I move the entire definition and declaration of my_exception into my_class.cpp, everything compiles fine and works correctly. Why is this, and how should I write this so that I could put the definition of the exception into the .h file? Or should I even put an error class definition into a .h file?

main.cpp:

#include my_class.h
int main(){
    my_class m;
    /* stuff */
}

my_class.h:

#ifndef MY_CLASS_H
#define MY_CLASS_H

#include <iostream>  //irrelevant for this
#include <exception>
using namespace std;

//taken from http://www.cplusplus.com/doc/tutorial/exceptions/
class my_exception : public exception{
    virtual const char* what() throw() { return "message";}
} me_err;

class my_class{
    my_class() };
};

#endif // MY_CLASS_H

my_class.cpp:

#include my_class.h
my_class::my_class(){ 
    throw me_err; 
}

Upvotes: 0

Views: 4361

Answers (1)

NathanOliver
NathanOliver

Reputation: 180710

The problem you are having is you created a global variable in your header file. When you compile main.cpp and my_class.cpp each one of them now has the same global variable. To fix this you can make me_err a member of my_class since that is what is using it.

Edit:

As pointed out by Fred Larson you could get rid of me_err entirely and just use throw my_exception;

Upvotes: 6

Related Questions