fgfjhgrjr erjhm
fgfjhgrjr erjhm

Reputation: 335

Undefined reference C++

I have a file called Student.h which have the static integers in this way:

    class Student
{
public:
    static int _avrA,_avrB,_avrC,_avrD;
};

and I have university.h that inherits Student.h . On the implementation of University.cpp , one of the functions returns:

return (_grade_average*(Student::_avrA/Student::_avrB))+7;

and the compiler writes:

undefined reference to Student::_avrA.

Do you know why it happens?

Upvotes: 2

Views: 3300

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75150

You have declared those variables, but you haven't defined them. So you've told the compiler "Somewhere I'm going to have a variable with this name, so when I use that name, don't wig out about undefined variables until you've looked everywhere for its definition."1

In a .cpp file, add the definitions:

int Student::_avrA; // _avrA is now 0*
int Student::_avrB = 1; // _avrB is now 1
int Student::_avrC = 0; // _avrC is now 0
int Student::_avrD = 2; // _avrD is now 2

Don't do this in a .h file because if you include it twice in two different .cpp files, you'll get multiple definition errors because the linker will see more than one file trying to create a variable named Student::_avrA, Student::_avbB, etc. and according to the One Definition to Rule Them All rule, that's illegal.

1 Much like a function prototype. In your code, it's as if you have a function prototype but no body.

* Because "Static integer members of classes are guaranteed to be initialised to zero in the absence of an explicit initialiser." (TonyK)

Upvotes: 9

Kerrek SB
Kerrek SB

Reputation: 477474

You have to define the static data members as well as declaring them. In your implementation Student.cpp, add the following definitions:

int Student::_avrA;
int Student::_avrB;
int Student::_avrC;
int Student::_avrD;

Upvotes: 2

Related Questions