Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
fgfjhgrjr erjhm Avatar asked Mar 20 '26 10:03

fgfjhgrjr erjhm


2 Answers

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)

like image 96
Seth Carnegie Avatar answered Mar 22 '26 00:03

Seth Carnegie


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;
like image 24
Kerrek SB Avatar answered Mar 21 '26 23:03

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!