user3126119
user3126119

Reputation: 323

C++ Constructor setting value

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.

Upvotes: 0

Views: 8093

Answers (3)

Proxy
Proxy

Reputation: 1854

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

Upvotes: 0

cageman
cageman

Reputation: 333

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.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227410

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

Upvotes: 8

Related Questions