CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2009
    Posts
    2

    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.

  2. #2
    Join Date
    Jan 2006
    Location
    Belo Horizonte, Brazil
    Posts
    405

    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.
    Last edited by ltcmelo; May 19th, 2009 at 09:11 PM. Reason: Added note.

  3. #3
    Join Date
    May 2009
    Posts
    2

    Re: Variables and Class Constructors

    Thanks

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    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_.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Variables and Class Constructors

    Using m_ as a prefix is quite a popular notation.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured