Search code examples
c++classcompiler-errorsheader-filesredefinition

Trying to use an object in another class's header file, getting "redefinition of class" error


I am currently trying to define a class "School" in a School.hpp file. Part of the School class is a vector of Student objects called roster. If I #include "Student.hpp" in School.hpp, the compiler throws "a redefinition of ‘class Student’" error. If I don't include Student.hpp, it throws a "'Student' was not declared in this scope" error for std::vector< Student>.

I don't know where it thinks I'm redefining the Student class as I only have the class definition for Student once, and that's in the Student.hpp file.

// School.hpp
#include <vector>
#include "Student.hpp"

class School
{
    // instance variables
    std::vector<Student> roster;

I'm new to C++ and working through some old school projects so apologies if this is a dumb mistake on my part.


Solution

  • It seems that you did not tell the preprocessor that the header file must be included once.

    On top of each header file ('*.hpp'), add this line:

    #pragma once
    

    For more info, see this article