tuks
tuks

Reputation: 790

C++ object instance as a class member

Sorry if the title is wrong, I don't know how else to name it.

I have a class Name:

class Name {
    char * name;
public:
    Name(const char * n){
        name = new char[strlen(n)+1];
        strcpy(name,n);
    }
    Name& operator=(const Name& n){
        name = new char[strlen(n.name)+1];
        strcpy(name, n.name);
        return *this;
    }
    Name(const Name& n){
        *this = n;
    }
};

And another class Person which should have Name object as it's member. How can I do this? I was thinking something like this:

class Person{
    double height;
    Name name;
public:
    Person(double h, const Name& n){
        height = h;
        name = n;
    }
};

But only this seems to work:

class Person{
    double height;
    Name * name;
public:
    Person(double h, const Name & n){
        height = h;
        name = new Name(n);
    }
};

Is it the right way to do it, and why can't I do it like I thought in the first place? Thanks

Upvotes: 3

Views: 508

Answers (2)

Your Name type does not have a default constructor, so you must initialize it in the initializer list in Person. Other than that, your operator= leaks memory and is unsafe for self-assignment and you never release the memory in a destructor, so there is another leak there.

Is there a good reason not to use std::string instead of your Name type?

Upvotes: 1

Igor Tandetnik
Igor Tandetnik

Reputation: 52621

Make the constructor like this:

Person(double h, const Name& n)
  : height(h), name(n)
{}

Then read about constructor initializer lists in your favorite C++ textbook.

The reason your original code doesn't work is that Name doesn't have a default constructor (a constructor that can be called with no parameters).

Upvotes: 2

Related Questions