3

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

1
  • 1
    PS. There is a memory leak in the copy constructor. Look up copy and swap idiom to help to it correctly. Commented Sep 16, 2013 at 4:58

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

How to deal with name(n) when n must be preprocessed or is the result of some computations ? Why is this syntax so awkward ? why is C++ so syntactically bizarre :D
1

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?

2 Comments

Thanks, I didn't mind memory leaks because I typed this code here quickly without testing it, it's just an example, not the real program I'm working on :)
@tuks: You should care about memory leaks. It is much easier to think for 5 min upfront who's responsible for the lifetime of the object than try to figure out after the fact and patch every place where you leak.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.