I am a beginner with OOP->I have a class Date with 3 private variable members and a should print the date in 2 ways:
- 12/25/2010
- December 25 2010
The following code it gives the error:
date.obj : error LNK2019: unresolved external symbol “public: __thiscall Date::Date(void)” (??0Date@@QAE@XZ) referenced in function “public: void __thiscall Date::printDate(void)” (?printDate@Date@@QAEXXZ)
What i am doing wrong?
date.h
#include<iostream>
#include<string>
#ifndef DATE_H
#define DATE_H
class Date
{
private:
int day;
int month;
int year;
public:
Date();
Date(int d, int m, int y)
{
day=d;
month=m;
year=y;
}
int getDay() const {return day;}
int getMonth() const {return month;}
int getYear() const {return year;}
void printDate(void);
};
#endif
date.cpp
#include"date.h"
#include<iostream>
#include<string>
const int NR=12;
void Date::printDate()
{
Date newDate;
std::string Months[]={"January","February", "March" , "April", "May", "June", "July", "August", "September", "Octomber", "November", "December"};
int position;
std::string month;
position=newDate.getMonth();
for(int i=0;i<NR;i++)
{
if(i==position)
{
month=Months[i];
}
}
std::cout<<month<<" "<<newDate.getDay()<<" "<<newDate.getYear()<<std::endl;
}
main.cpp
#include "date.h"
#include <iostream>
int main()
{
int d;
int m;
int y;
std::cout<<"Enter day: ";
std::cin>>d;
std::cout<<"Enter month: ";
std::cin>>m;
std::cout<<"Enter years: ";
std::cin>>y;
Date newDate(d,m,y);
std::cout<<newDate.getMonth()<<"/"<<newDate.getDay()<<"/"<<newDate.getYear()<<std::endl;
newDate.printDate();
}
The error is quite clear: you declared constructors for your
Dateclass but didn’t define them inside the cpp file.You should add definitions for these constructors. They could just look like this:
or maybe
which at least wouldn’t print nonsense if you call
EDIT:
As suggested by Mat, you should use constructor initializer lists when you can. Your other constructor which uses parameters would look like this with an initialization list:
In your case, your constructor calls the empty constructor on
day,monthandyearand then assigns values to them, whereas when using initialization lists, theDateconstructor calls constructors with parameters forday,monthandyear.