user1082764
user1082764

Reputation: 2015

How to pass a constructor through another constructor

I have classes Date and Time. I am creating a class Onetime with a public constructor but i am not sure how i can create a new date and time inline.

schedule[0]= new Onetime("see the dentist", 
  Date(2013, 11, 4), 
  Time(11, 30, 0), 
  Time(12, 30, 0));

class Onetime {
  public: 
    Onetime(  // what should I put here?  )
}

Upvotes: 2

Views: 103

Answers (3)

John Kugelman
John Kugelman

Reputation: 361556

Declare the class as such, using either Date and Time or const Date & and const Time & for the date and time parameters. In general const & is appropriate for large objects to prevent them from being unnecessarily copied. Small objects can use const & or not, whichever you prefer.

// Onetime.h

class Onetime {
  public: 
    Onetime(const std::string &description,
            const Date &date,
            const Time &startTime,
            const Time &endTime);

  private:
    std::string description;
    Date        date;
    Time        startTime, endTime;
};

Then define the constructor in your .cpp file. Use : to denote an initializer list to initialize the member variables.

// Onetime.cpp

Onetime::Onetime(const std::string &description,
                 const Date &date,
                 const Time &startTime,
                 const Time &endTime)
    : description(description),
      date(date), startTime(startTime), endTime(endTime)
{
}

Finally, you can create a Onetime object exactly as you wrote. You could even omit the new keyword if you wish. new is for allocating objects on the heap, which you don't always need to do in C++ (unlike Java or C#, say).

schedule[0] = new Onetime("see the dentist", 
  Date(2013, 11, 4), 
  Time(11, 30, 0), 
  Time(12, 30, 0));

Upvotes: 2

apartridge
apartridge

Reputation: 1820

You can do,

class Onetime {
  public: 
    Onetime(const std::string& message, const Date& date, const Time& start, const Time& end);
  private:
    std::string m_message;
    Date m_date;
    Time m_start;
    Time m_end;
 }

and

Onetime::Onetime(const std::string& message, const Date& date, const Time& start, const Time& end)
: m_message(message), m_date(date), m_start(start), m_end(end) 
{

}

Try to avoid new as that is heap-allocated memory and expensive to get (compared to stack-based memory.)

Upvotes: 1

6502
6502

Reputation: 114461

This the standard approach

class Onetime {
    std::string description;
    Date date;
    Time from_time;
    Time to_time;

    Onetime(const std::string& description,
            const Date& date,
            const Time& from_time,
            const Time& to_time)
    : description(description),
      date(date),
      from_time(from_time),
      to_time(to_time)
    {
       ... rest of initialization code, if needed ...
    }
  ...
};

Upvotes: 5

Related Questions