0

I'm still learing c++ and was following an example from my book. I basically copied their code and added the include and namespace. What am I doing wrong?

Code:

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

class Date{
  int y,m,d;
public:
  Date(int y, int m, int d);
  int month(){return m;}
  int day(){return d;}
  int year(){return y;}
};

int main(){
  Date b{1970,12,30};
cout<< b.month()<< '\n';
}

Trying to compile with g++ -std=c++11 -o test2 test2.cc

Error:

Date::Date(int, int, int)           /var/tmp//ccGuivAs.o
ld: fatal: Symbol referencing errors. No output written to main    
collect2: ld returned 1 exit status
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Gely
  • 21
  • 1
  • 1
  • 2

4 Answers4

1
Date(int y, int m, int d);

The error message is signaling (in an admittedly unclear way) that there's no definition for Date. It's declared, but not defined. You didn't specify what the constructor does.

Date(int y, int m, int d) {
    this->y = y;
    this->m = m;
    this->d = d;
}

Or, better, using initializer list syntax:

Date(int y, int m, int d): y(y), m(m), d(d) { }
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I added : y(y), m(m), d(d) { } to my Date(int y, int m, int d): as suggested and I'm no longer getting error (YAY!). But it isn't printing out anything in main now. It feels like I'm stuck in my class. – Gely Sep 28 '14 at 15:05
1

You have to add implementation (definition) of constructor

Date(int y, int m, int d);

At the moment there is only a declaration found in your Date class and such a situation results in

undefined reference to `Date::Date(int, int, int)' collect2: error: ld returned 1 exit status

http://ideone.com/wMgbKX

4pie0
  • 29,204
  • 9
  • 82
  • 118
0

You declared the Date::Date constructor, but never defined it.

Your declaration is a promise to the compiler that the constructor Date::Date will be defined somewhere. But you never actually provided a definition. That is what's causing the error.

You can provide a definition right there, inside the class definition, like you did with other member functions. Or you can provide a definition outside the class. It is up to you. But a definition has to be provided somewhere.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

You need to implement Date::Date(int, int, int) (i.e. the Date constructor) somewhere, as explicitly stated by your compiler. You could do that by adding a body to it, like for its month, day and year methods, or outside of the class.

rems4e
  • 3,112
  • 1
  • 17
  • 24