Reputation: 99
new to c++ and cant figure out why visual studio doesn't like my "HealthProfile person.setFirstName(first)" line of code. The error is with "person" and the error is no default constructor. It's probably something painfully obvious, but my code is almost identical from the code in my book. Thanks in advance!
main:
#include <iostream>
#include "HealthProfile.h"
using namespace std;
int main()
{
string first;
HealthProfile person;
cout << "Enter first name" << endl;
getline(cin,first);
person.setFirstName(first);
}
header:
#include <string>
using namespace std;
class HealthProfile
{
public:
HealthProfile(string, string, string, int, int, int, int, int);
void setFirstName(string);
string getFirstName();
void setLastName(string);
string getLastName();
};
function:
#include <iostream>
#include "HealthProfile.h"
using namespace std;
HealthProfile::HealthProfile(string first, string last, string g,
int m, int d, int y, int h, int w)
{
setFirstName(first);
setLastName(last);
setGender(g);
setMonth(m);
setDay(d);
setYear(y);
setHeight(h);
setWeight(w);
}
void HealthProfile::setFirstName(string first)
{
firstName = first;
}
string HealthProfile::getFirstName()
{
return firstName;
}
void HealthProfile::setLastName(string last)
{
lastName = last;
}
string HealthProfile::getLastName()
{
return lastName;
}
Upvotes: 0
Views: 4356
Reputation: 1691
This line in main:
HealthProfile person;
Declares an instance of the HealthProfile class using a default constructor. You've not declared a default constructor. Creating your own custom constructor prevents a default constructor from being implicitly created for you. If you want to use a default constructor as well as a custom one, you need to explicitly declare and define it. If you don't want to use a default constructor, then pass in arguments to use your custom one.
To declare a default constructor in your .h:
HealthProfile();
And to define it in your .cpp:
HealthProfile::HealthProfile() { }
Or to simply call your existing custom constructor in main:
HealthProfile person(first,last,g,m,d,y,h,w); // AFTER collecting values for these arguments
Upvotes: 4
Reputation: 842
There is nothing wrong with setFirstName()
.
The issue is that you've declared a constructor that takes three strings
and five ints
, this removes the default constructor which you are using when you call HealthProfile person
The solution is to either use the HealthProfile
cosntructor and pass it three strings
and five ints
, or to declare and define a constructor that takes no parameters by adding HealthProfile(){}
to the header.
Upvotes: 6