velkoon
velkoon

Reputation: 962

Error creating a class object

I am having a problem creating a simple class object. I created a small program to simulate the problem. I have a class "Person" with data members string name, string eye_color, and int pets. When I call Person new_person("Bob", "Blue", 3), my debugger shows this as the new_person's value:

{name=""eye_color=""pets=-858993460}

I'm looking at previous projects where I had no problems with this and am not spotting anything...What am I missing?

person.h

#include <iostream>
#include <string>

class Person
{
public:
    Person(std::string name, std::string eye_color, int pets);
    ~Person();

    std::string name;
    std::string eye_color;
    int pets;
};

person.cpp

#include "person.h"

Person::Person(std::string name, std::string eye_color, int pets)
{
    this->name;
    this->eye_color;
    this->pets;
}
Person::~Person(){}

city.h

#include "person.h"

class City
{
public:
    City();
    ~City();

    void addPerson();
};

city.cpp

#include "city.h"

City::City(){}
City::~City(){}

void City::addPerson(){
    Person new_person("Bob", "Blue", 3);
}

main.cpp

#include "city.h"

int main(){
    City myCity;

    myCity.addPerson();
}

Upvotes: 1

Views: 122

Answers (1)

OJ7
OJ7

Reputation: 317

It doesn't look like you are actually assigning the values in the Person class so that is why you are getting random values for those data members.

It should be:

Person::Person(std::string name, std::string eye_color, int pets)
{
    this->name = name;
    this->eye_color = eye_color;
    this->pets = pets;
}

Upvotes: 2

Related Questions