I am borring this example from the material i am going over. According to textbook, all is well here.
Yet, when trying to compile these files, i am getting a problem (see below)
3 files
Date.cpp:
#include "Date.h"
Date::Date()
{
setDate(1,1,1900);
}
Date::Date(int month, int day, int year)
{
setDate(month, day, year);
}
Date.h:
class Date
{
public:
Date ();
Date (int month, int day, int year);
void setDate(int month, int day, int year);
private:
int m_month;
int m_day;
int m_year;
};
Main.cpp:
#include "Date.h"
int main ()
{
Date d1 ;
return 1;
}
When trying to compile with g++ *, i get
Undefined symbols for architecture x86_64:
"Date::setDate(int, int, int)", referenced from:
Date::Date() in cc8C1q6q.o
Date::Date() in cc8C1q6q.o
Date::Date(int, int, int) in cc8C1q6q.o
Date::Date(int, int, int) in cc8C1q6q.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
When i declare Date *d; instead, program compiles.
When i declare Date *d = new Date instead, program fails.
What’s going on here please?
You haven’t provided a
setDatemethod for your class. You declare it in the header file but you need to provide actual code for it as well.The error you’re seeing is the linker (
ld) telling you that, although you have a piece of code trying to call that method, the linker has no idea where it is.You need to provide the method, such as putting the following into
Date.cpp: