default constructor

This is a discussion on default constructor within the C++ Programming forums, part of the General Programming Boards category; Code: class base{ private: int x; public: base(){ x=4; } }; is it correct to do this? set x=4 in ...

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

    default constructor

    Code:
    class base{
       private:
            int x;
       public:
           base(){
             x=4;   
         }
    };
    is it correct to do this? set x=4 in a default constructor? want'ed to set the initial value of a variable in class that gets created by a default constructor.

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,160
    Your question is, is it correct to properly initialize an object? Well... yes?

    The only thing that isn't quite right is that you should initialize members like this:

    Code:
    base::base()
      : x( 4 )
    {
    }
    Instead of what you have there (i.e., use the initializer list)
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating array of objects w/o default constructor
    By QuestionC in forum C++ Programming
    Replies: 19
    Last Post: 05-02-2007, 08:03 PM
  2. template class default constructor problem
    By kocika73 in forum C++ Programming
    Replies: 3
    Last Post: 04-22-2006, 09:42 PM
  3. constructors
    By shrivk in forum C++ Programming
    Replies: 7
    Last Post: 06-24-2005, 09:35 PM
  4. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 03:50 AM
  5. no default constructor error
    By 7stud in forum C++ Programming
    Replies: 8
    Last Post: 08-23-2003, 01:35 AM

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