Thread: Why is the above code working???

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    225

    Why is the above code working???

    Code:
    #include <iostream.h>
    class room
    {
      int length;
      int width;
      public:
    	  room(int l=10,int w=0):
    	  width(w),
    	  length(l)
    	  {
    	  }
    	  void putdata()
    	  {
    		  cout<<length<<" ";
    		  cout<<width<<" ";
    		  endl;
    	  }
    };
    
    int main(void)
    {
     room objroom1;
     room objroom2(12,8);
     objroom1.putdata();
     objroom2.putdata();
    
    
     getch();
     return 0;
    }
    just see the constructor?and please tell me how is it working perfectly?see the : at the end of room and see the pair of empty braces if you remove them the code isn't working! Please tell me what is the compiler interpreting from this?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Code:
    room(int l=10,int w=0):
    	  width(w),
    	  length(l)
    	  {
    	  }
    The green part is called initialiser list, where width and height are initialised with w and l respectively. (However, note that the members should be initialized in the same order they are declared in the class - otherwise you might get into problems when you try to use already initialised members to initialise others.)

    The part between the curly braces is the constructor body where you might perform other things beyond initialisation of members. Every function definition naturally needs a body (even if it is empty), so it would be incorrect to omit them.

    As to style, perhaps rename the putdata method to print or output or something similar, as it is not obvious what data is put where.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Thanks Anon

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code not working?
    By Elysia in forum C++ Programming
    Replies: 12
    Last Post: 04-06-2009, 01:57 AM
  2. Replies: 3
    Last Post: 02-24-2009, 08:49 PM
  3. C code not working
    By D3ciph3r in forum C Programming
    Replies: 2
    Last Post: 05-27-2005, 04:13 PM
  4. Trying to eject D drive using code, but not working... :(
    By snowfrog in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2005, 07:47 PM
  5. Linked List Working Code
    By Linette in forum C++ Programming
    Replies: 9
    Last Post: 01-24-2002, 12:00 PM