Search code examples
c++visual-studio-codelinker-errorsgnuclion

Linking c++ code: undefined reference to `Student::Student(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double)


Every time I build my code I get this error. I tried different projects and it's the same thing. It appeared in vscode and CLion; however I tried the code on <Relp.it> and it was working.

#include <iostream>
#include <string>
using namespace std;

class Student{

private:
    std::string name;
    double grade;

public:
    //public constructor to reach it
    Student (std::string s, double g);

    void setName(std::string n){
        name = n;
    }

    void setGrade(double g){
        grade = g;
    }

    std::string pass(){
        //if grade greater than 60 print "yes" if not print "no"
        return (grade > 60 ? "yes": "no");
    }

    void printStatus(){
        cout << "name:" << name << endl;
        cout << "grade: " << grade << endl;
        cout << "Pass: " << pass() << endl; 
        cout << endl;
    }

};



int main(){

    Student Barrak("Barrak", 96);
    Barrak.printStatus();
    Barrak.pass();


    return 0;
};

and this is what i get.

PS C:\Users\barra\Desktop\ab> cd "c:\Users\barra\Desktop\ab\" ; if ($?) { g++ main.cpp -o main } ; if ($?) { .\main }
c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\barra\AppData\Local\Temp\cc1itdQl.o:main.cpp:(.text+0x54): undefined reference to `Student::Student(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, double)'
collect2.exe: error: ld returned 1 exit status
PS C:\Users\barra\Desktop\ab> 


Solution

  • The problem is that you've only declared the parameterized constructor Student (std::string s, double g); but not defined it. So the linker cannot find it when needed and hence gives the mentioned error.

    To solve this problem you can add the definition for this constructor as shown below:

    class Student{
    
    private:
       //other members as before
    
    public:
        //DECLARATION FOR PARAMETERIZED CONSTRUCTOR
        Student (std::string s, double g);
    
        //other members as before
    
    };
    
    //DEFINE PARAMETERIZED CONSTRUCTOR
    Student::Student (std::string s, double g): name(s), grade(g) //this uses constructor initializer list to initiliaze name and grade
    {
        
    }
    

    The output of the modified program can be seen here.

    Method 2

    You can also define the parameterized constructor inside the class in which case it will be implicitly inline as shown below:

    class Student{
    
    private:
        std::string name;
        double grade;
    
    public:
        //DEFINITION FOR PARAMETERIZED CONSTRUCTOR
        Student (std::string s, double g): name(s), grade(g)
        {
            
        }
    
        //other members as before
    
    };