class constructor

This is a discussion on class constructor within the C++ Programming forums, part of the General Programming Boards category; Hi, i got a class: Code: class base{ private: int age; public: base(int); }; The constructor can be: method A: ...

  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
    21,650
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 04: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, 12:47 PM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21