2

I'm making a calendar application in c++ and I'm making a great number of overloaded constructors for the appointment class depending on the information provided(e.g. if i have a start time for the event but no end time, and a location, but no attached contacts)

class Appointment {
    public:
    //overloaded Constructors
    Appointment();
    Appointment(Date);
    Appointment(Date,Date);
    Appointment(Date,Date,std::string);
    Appointment(Date,Date,std::string,std::string);
    Appointment(Date,Date,std::string,std::string,Contact);

etc. etc. Is there a better way to do this?

austinphilp
  • 57
  • 1
  • 9
  • What about creating an object and setting its properties afterwards via getter/setters ? (or default ones if you support them) – Marco A. Sep 25 '14 at 22:25
  • 3
    It really depends on what these constructors do. If for example do the same job you could just use a simple constructor with default arguments and avoid code bloat. – 101010 Sep 25 '14 at 22:25
  • I didn't know about default parameters, that should work nicely for what I want to do, thank you! – austinphilp Sep 25 '14 at 22:32
  • I generally use the constructor to do the minimum required to put the object into a valid state to prevent Undefined Behaviour. Everything else through the normal interface. Most rules have their exceptions though depending on the situation. – Galik Sep 25 '14 at 22:46
  • Sounds like it might be a perfect application for the [named parameter idiom](http://www.parashift.com/c++-faq/named-parameter-idiom.html). – Mark Ransom Sep 25 '14 at 23:03

2 Answers2

3

You could either:

  • Create the object (a valid one) and set its properties afterwards via interface setters (since it seems an object can have a variable number of properties this seems like a good choice)

  • Use default parameters, e.g.

    Appointment(Date=getDefaultDate(),
                Date=getDefaultDate(),
                std::string=getDefaultString(),
                std::string=getDefaultString(),
                Contact=getDefaultContact());
    

It really boils down to how you prefer to handle and initialize your objects.

An important sidenote: in large production codebases default parameters is a C++ feature often frowned upon because it might hinder readability and/or render debugging more difficult in particular scenarios (especially when something unwanted goes on and you didn't consider a default parameter being chosen, default parameters are specified on the declaration and that might also "hides" a potential problem from the developers)

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246
0

This is totally unnecessary. As pointed out Macro A , you can default construct the object and afterwards you can use setters for them.

One more thing when designing a software you should keep in mind the rule of complete and minimal i.e you should provide all facilities in a class avoiding duplication/redundancy.

ravi
  • 10,994
  • 1
  • 18
  • 36