Thread: class constructor

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    58

    class constructor

    Hi,
    i got a class:
    Code:
    class base{
    private:
    	int age;
    public:
    	base(int);
    };
    The constructor can be:
    method A:
    Code:
    base::base(int _age):age(_age){
    }
    method B:
    Code:
    base::base(int _age){
        age=_age;
    }
    are both the methods correct? is it correct in c++ to use method B?

    do clarify.
    thanks

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    Yes, they are both correct. There is no difference between them
    EDIT: See Initialization List in C++

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Although it is true that in this case there is no real difference between the two since age is of a built-in type, the difference between appropriate construction and default construction + assignment for a member variable of class type may be significant. Furthermore, const and reference member variables, as well as those of types without a default constructor, must be initialised using the initialisation list.
    Last edited by laserlight; 05-16-2009 at 11:16 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  3. template class default constructor problem
    By kocika73 in forum C++ Programming
    Replies: 3
    Last Post: 04-22-2006, 09:42 PM
  4. Calling constructor of the base class of a derived class..
    By CaptainPenguin in forum C++ Programming
    Replies: 5
    Last Post: 02-19-2003, 01:47 PM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM