tags:

views:

130

answers:

3

I am running a C++ program which uses a class from another .cpp file. The class only has a constructor. It works when I test it separately. The main program compiles,but when I run it, I have a bug in the constructor. Any one can think of any situation that could happen? Thanks.

I guess I just run the code in terminal, and it is fine. But when I try to build a project in eclipse, it shows following code has multiple definition error:

class model
{
  public:
    int textures [];
    float vertices[][3];
    float triangles[][13];
  public:
    model(const char*); // constructor
};

model::model(const char* filename)
{

error message is: multiple definition of `model::model(char const*)'

any idea?

+2  A: 

Anyway, I'll venture a random guess (given what you've posted, there little to go on). I'll guess that you've overflowed your triangle array (perhaps counter is too big) and you're trashing your heap or stack.

One more thing. This line:

if (str[0] != '#' and !str.empty())

is buggy. If str is empty, you don't want to be reading str[0]. You need to switch the order around:

if (!str.empty() and str[0] != '#')
R Samuel Klatchko
Actually, `and` is the same as ` try it out. In C, it was required you included `iso646.h`, but in C++ they are implicitly available. They are called alternative tokens, and you can find them in section 2.5. I personally dislike the practice of using them.
GMan
@GMan - thanks, I never knew that corner of the language before.
R Samuel Klatchko
No problem, it's a strange corner indeed.
GMan
+2  A: 

You need to split your code into a .h (header) and a.cpp (implementation) file and put:

model::model(const char* filename)
{

in the latter. Or, rewrite your class so the definition of the constructor (and any other member functions) is inside the class in the header file:

class model {
   ...
   model(const char*) {
     // constructor body here
   }
};
anon
A: 

The error happens because you get a new definition of the function every time your header is included somewhere. If it is is used in more than one place in the program, you get the error.

You probably want to define the constructor either in a separate implementation file (class goes to header so that others can use it, function implementations go to .cpp/cc files). Alternatively you can define it within the class block instead of doing it outside.

Tronic