0

I am trying to write a constructor in C++ (I am new).

My Attempt:

class Tree
{
    private:
        int leaf;

    public:
        Tree(int leaf); //constructor
};

Tree::Tree(int leaf) //constructor
{
strcpy(this->leaf, leaf);
}

Is this the proper way how to do it? Since I found many different version with srcpy, without , etc.

4
  • possible duplicate of Initializing fields in constructor - initializer list vs constructor body Commented Jan 5, 2014 at 21:35
  • 6
    Would you kindly do us a favour and help us understand how people learn C++ -- please explain why did you feel that strcpy was appropriate here? I'm genuinely curious about the thought process. Commented Jan 5, 2014 at 21:37
  • 1
    I'm sorry to see that you did not read my answer on your previous question, or Google strcpy to find out what it does. Commented Jan 5, 2014 at 22:03
  • @LightnessRacesinOrbit "What does this code do? It burns the eyes of children." Hahaha Commented Jan 5, 2014 at 22:56

3 Answers 3

8

No, it is not. strcpy is for copying null-terminated strings. Use the constructor initialization list:

Tree::Tree(int leaf) : leaf(leaf) {}

Also note that your constructor allows for implicit conversions from int to Tree. So you can do this kind of thing:

Tree t = 4 + 5;

If you do not want this behaviour, mark the constructor explicit:

explicit Tree(int leaf);
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply initialize the int like this:

Tree::Tree(int leaf) //constructor
  : leaf(leaf)
{
}

strcpy is not needed, it is meant for C-strings. It does not compile since it expects a char* pointer.

5 Comments

so if you use a string (char* ) you have to use strcpy then?
@user3126119, I suggest using a std::string and doing the exact same thing as this. @cage, It initializes it, not assigns.
Do yourself a favor and don't use C-strings (char*). Use C++ strings (std::string) which can be initialized like your int.
@cageman it's initialization, not assignment. Also, strcpy won't compile here, fixed that in your answer.
can you edit my code with std::string since I cannot figure how to do it I have been trying and still no success. I would appreciate a lot
0

You can use std::copy if you really want to use some sort of memory-copying function, but m_leaf = leaf works just as well and is easier to read. Notice my use of m_leaf instead of leaf - it's common to add the prefix m_ before all member variables (More on Hungarian Notation here).

Comments

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.