Question about defining classes

This is a discussion on Question about defining classes within the C++ Programming forums, part of the General Programming Boards category; Hey, I am just wondering if a class definition can include two constructors, such as the following: Year(int days = ...

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

    Question about defining classes

    Hey, I am just wondering if a class definition can include two constructors, such as the following:

    Year(int days = 365, int weeks = 52, int months = 12);
    Year();

    Thanks (my intuition says yes and that the empty constructor would yield random values for the arguments...but my intuition tends to be wrong a lot )

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    class Year
    {
    	Year(int days = 365, int weeks = 52, int months = 12);
    	Year();
    };
    
    
    int main()
    {
    	Year y; // Which constructor?
    }
    But you may have more than one constructor. You can't just set all defaults like that though.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    16
    Ah yep, makes sense. Thanks for the assistance.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Your class can have two (or more) constructors, but not like you posted. Constructors follow the same rules as regular functions in this situation.

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    Classes can have as many constructors as reasonably required; think std::string

    Code:
    std::string a = 'a';
    std::string b = "b";
    std::string c = a + b;
    The main point is to avoid ambiguity. For example, you shouldn't really provide a constructor for each of two objects which easily cast to each other.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes question...
    By Raigne in forum C++ Programming
    Replies: 24
    Last Post: 09-12-2006, 02:46 AM
  2. Replies: 2
    Last Post: 07-28-2006, 03:59 PM
  3. Simple Question about Classes
    By Loctan in forum C++ Programming
    Replies: 5
    Last Post: 06-26-2006, 03:40 AM
  4. Classes and Win32 API, and another Question
    By philvaira in forum Windows Programming
    Replies: 10
    Last Post: 04-10-2004, 08:21 PM
  5. Newbie question about the Private type in classes
    By Ryeguy457 in forum C++ Programming
    Replies: 1
    Last Post: 09-07-2002, 11:17 PM

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