Reputation: 2691
If I have different attributes in my class, for example following code:
class Position
{
double latitude;
double longitude;
double altitude;
PosixTime time;
};
So we say this is the class I want to construct, where time
is (at current time of development) always the current time. I currently don't use any other times, it's always the creation time. Should I still implement a constructor with a time parameter? Maybe it's used later or by another developer? Summarized there two options:
Writing only 2 constructors:
Position()
: latitude(0)
, longitude(0)
, alitutde(0)
, time(PosixCurrentTime()) {}
Position(double lat, double lon, double alt)
: latitude(lat)
, longitude(lon)
, alitutde(alt)
, time(PosixCurrentTime()) {}
Writing 3 constructors (both from top and the following):
Position(double lat, double lon, double alt, PosixTime t)
: latitude(lat)
, longitude(lon)
, alitutde(alt)
, time(t) {}
Upvotes: 0
Views: 71
Reputation: 21520
If time is (at current time of development) ALWAYS the current time, then you can declare only a get method:
class Position {
public:
static Posixtime getCurrentTime() const;
private:
double latitude;
double longitude;
double altitude;
};
This is an option, otherwise you should have only one constructor with all default values:
class Position {
public:
Position(const double& = 0, const double& = 0, const double& = 0, const PosixTime& = getCurrentTime())
};
Position::Position(const double& lat, const double& lon, const double& alt, const PosixTime& t) :
latitude(lat),
longitude(lon),
altitude(alt),
time(t) {
}
Upvotes: 0
Reputation: 109119
Whether you provide a constructor that allows setting the time
to some arbitrary value or not is a design decision you should make depending on the semantics of the class. Think of future use cases, and whether that functionality would make sense. If you do decide on that, you could merge constructors 2 and 3 into a single one.
Position(double lat, double lon, double alt, PosixTime t = PosixCurrentTime())
: latitude(lat)
, longitude(lon)
, alitutde(alt)
, time(t) {}
And if your compiler supports C++11, define the class as
class Position
{
double latitude = 0;
double longitude = 0;
double altitude = 0;
PosixTime time = PosixCurrentTime();
public:
Position() = default;
Position(double lat, double lon, double alt, PosixTime t = PosixCurrentTime())
: latitude(lat)
, longitude(lon)
, alitutde(alt)
, time(t) {}
};
Upvotes: 2
Reputation: 16328
You only need one constructor, with default values for its parameters.
Position(double lat = 0, double lon = 0, double alt = 0, PosixTime t = get_current_time())
: latitude(lat), longitude(lon), alitutde(alt), time(t)
{
}
Notice that in this example get_current_time()
is a placeholder for the function that returns you the current time.
Upvotes: 2