1

I am trying to initialize a Student object and I keep getting an undefined reference error despite having the class definitions in my header file.

I have the C++ file student.cpp:

class Student {
private:
    double gpa;
public:
    Student(double g) : gpa(g) {};
    double getGPA() {return gpa;}
};

The associated header file student.h:

#ifndef STUDENT_H
#define STUDENT_H

class Student 
{
private:
    double gpa;
public:
    Student(double);
    double getGPA();
};

#endif

And the C++ source file main.cpp:

#include "student.h"

int main() {
    Student myStudent(4.0);
    return 0;
}

I am running the command g++ main.cpp student.cpp to link the source files. It keeps giving an error:

"main.cpp:(.text+0xe): undefined reference to `Student::Student(double)".

Why is this happening?

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
ewaddicor
  • 29
  • 2
  • 1
    Whatever resource taught you that this is the right way to implement methods, you need to ditch it and get [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – Yksisarvinen Nov 09 '22 at 20:45
  • Did you link both object files together into the final executable? – tadman Nov 09 '22 at 20:45

1 Answers1

2

student.cpp should not redeclare the whole class, it should just add definitions for the class methods

#include "student.h"

Student::Student(double g) : gpa(g) {}

double Student::getGPA() {
    return gpa;
}

then leave the class definition, with the method declarations, in student.h

Also make sure you actually link after you compile the cpp files.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218