Variables and Class Constructors
I was just wondering what the best way is to assign private variables a value within the constructor.
For example;
Option 1: //Which uses the private variable directly
Book::Book(string author)
{
_Author = author;
}
or Option 2 //Call a method to do it for me
Book::Book(string author)
{
AddAuthor(author);
}
With option 2, its invoking its public method and I could have checks stopping null values etc however it would be using more memory? I could really do the same thing in option 1, how ever would it be creating redundant code since I have a Method that does it?
thanks in advance.
Re: Variables and Class Constructors
In C++ you should not use any of the strategies you mentioned. The best (and only) way to do such initialization is in the constructor's initialization list. In addition, you should pass the string by a reference to const (not by value) in this case.
Code:
Book::Book(const string & author) : _Author(author)
{
}
You might wanna check the FAQ for a detailed explanation.
Note: I said only above because the strategies you mentioned do not initialize. They simply assign.
Re: Variables and Class Constructors
Re: Variables and Class Constructors
By the way, names that begin with an underscore followed by an uppercase letter, or that contain double underscores, are reserved to the implementation for any yse. As such, _Author is reserved to the implementation for any use.
I suggest changing convention to a trailing underscore, e.g., Author_.
Re: Variables and Class Constructors
Using m_ as a prefix is quite a popular notation.