I wanted to try to make a simple factoring program just to try to use a class in a separate file and try using a constructor. When I try to compile I get this error: "in function 'main' [Linked error] undefined reference to 'Factor::Factor(int)' " and "Id returned one exit status [build error] ["Factoring] error 1
int main(int argc, char *argv[])
{
int number;
cout << "Enter a number to be factored. ";
cin >> number;
Factor numb(number);
system("PAUSE");
return 0;
}
this is my header file
#ifndef FACTOR_H
#define FACTOR_H
/*
* Factors integers
*/
class Factor
{
public:
// class constructor
Factor(int);
//Factorize function
void Factorize(int);
};
I tried that and got the following errors:
in line 3 "In file inlcuded from main.cpp"
in line 3:1 "unterminated #ifndef
in line 7: "Declaration of 'Factor::Factor(int)' outside of class is not a definition"
Okay, we determined what's wrong here. You didn't end your pre-processor if statement. So take Factor::Factor(int); out of the main cpp file again, and change your header from:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef FACTOR_H
#define FACTOR_H
/*
* Factors integers
*/
class Factor
{
public:
// class constructor
Factor(int);
//Factorize function
void Factorize(int);
};
to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef FACTOR_H
#define FACTOR_H
#endif
/*
* Factors integers
*/
class Factor
{
public:
// class constructor
Factor(int);
//Factorize function
void Factorize(int);
};
EDIT: Using code tabs would probably have made this easier to read. Might be something to look in to in the future.
Undefined references occur when an invoked function doesn't have an associated definition. For instance, consider this example:
1 2 3 4 5 6
int Function();
int main()
{
return Function();
}
What do you notice? I'll tell you; Function() is never defined; that is, it's never given a body. By omitting the body of a function, you fail to give the linker the information it needs to assemble the function. To fix this, you would add the following after main():
1 2 3 4
int Function()
{
return(0);
}
To define a method (a function that resides within a class), you would qualify the method with the identifier of the class followed by the scope resolution operator, as such:
1 2 3 4 5 6 7 8 9 10 11
class COMyClass
{
public:
void MyMethod();
};
// Define the method:
void COMyClass::MyMethod()
{
// ...
}
I think I have the methods defined in the factor class's .cpp file. I'm new to using classes though so maybe I have them defined incorrectly or in the wrong place
@cheZ: You do have the definitions in the class' cpp file.
@Framework: Prototyping the call forces the call to be "correct" according to the order of operations, which can force the compiler/debugger to tell you more about why it's an undefined reference.
I'm not questioning that. I'm saying that in this case, I used it as a debugging tool to force the compiler to spit out different errors that can help triangulate the actual problem.