Help with Pointers and Classes

I'm trying to write a class Person that has the following fields: name (string), best_friend (Person*) - a pointer to a Person's best friend, and popularity (int).

I started to write the class declarations and I got an error for the line below which I have commented out.

Error: Assigning to 'Person *' from incompatible type 'Person'
Can someone please tell me what I'm doing incorrectly and how to fix it? Thank you in advance.

class Person{
public:
Person();
Person(string new_name, int new_popularity, Person* new_best_friend);
void set_best_friend();

private:
string name;
int popularity;
Person* best_friend;

};

Person :: Person()
{
name = "";
popularity = 0;
//*best_friend = Person(); ERROR WAS IN THIS LINE!

}

Person :: Person (string new_name, int new_popularity, Person* new_best_friend)
{
name = new_name;
popularity = new_popularity;
best_friend = new_best_friend;
}
You were trying to assign an object to a pointer to that object. Then you changed it to assign newly created person to dereferenced pointer, but that didn't work because you do not have assigment operator defined and in any case you are dereferencing invalid pointer, so it will crash anyway. Then you commented out that line and posted here your first error. Either that or you were experimenting with block comments.

You want to assign address, like that: best_friend = new Person(). However doing so will lead to infinite recursion in your constructor and crash. Even if it wasn't the case, you still have memory leak: if you change your best friend, you wil leak default one.

It is better to assume that there is no best friend in default created person and set best_friend pointer to null, or forbid default creating Person.
Topic archived. No new replies allowed.