Home > Software engineering >  getters and setters for composit members C
getters and setters for composit members C

Time:06-09

I am learning C and I am having some trouble wrapping my head around getters and setters for objects that are members of other objects.

I have a DateOfBirth class with int month, int day, int year, and its appropriate getters and setters. I would like to have an instance of the DateOfBirth class as a private member of another class.

What would be the correct implementation for the getters/setters inside the container class?

CodePudding user response:

Depends on how expensive to copy DateOfBirth is. Since yours stores just a few ints, I'd write a getter/setter as usual:

const DateOfBirth &GetDate() const {return date;}
void SetDate(DateOfBirth new_date) const {date = new_date;}

But remember that there's no single correct implementation, what kind of setter to use depends on why you need it in the first place. If you don't need any custom logic on reading/writing the member (and don't anticipate needing it in the future), you can make the member public.

If the class is expensive to copy, you could make a setter return a non-const reference: DateOfBirth &SetDate() {return date;}, but this severely limits what logic you can add to the setter latter, at this point you might as well make the member public.

You could also implement setters for individual sub-members.

Or you could make the "setter" accept a function/lambda, which is given a non-const reference to the member as a parameter:

void SetDate(auto &&setter) {decltype(setter)(setter)(date);}
// Then:
x.SetDate([](DateOfBirth &date){date = ...;});

CodePudding user response:

One crude way(that matches your current given description) is as shown below:

class DateOfBirth 
{
  private:
    int month = 0, day = 0, year = 0;
  public:
    //getters 
    int getMonth() const 
    {
        return month;
    }
    int getDay() const 
    {
        return day ;
    }
    int getYear() const 
    {
        return year;
    }
    //setters
    void setMonth(int pmonth) 
    {
        month = pmonth;
    }
    void setDay(int pday)
    {
        day = pday ;
    }
    void setYear(int pyear)
    {
        year = pyear;
    }
};
class AnotherClas 
{
  DateOfBirth d; 
  public:
    //getter 
    DateOfBirth getDateOfBirth() const 
    {
        return d;
    }
    //setter 
    void setDateOfBirth(int pmonth, int pday, int pyear)
    {
        d.setMonth(pmonth); //set month 
        d.setDay(pday);     //set day 
        d.setYear(pyear);   //set year 
    }
};
int main()
{
    //create instance of another class 
    AnotherClas a; 
    a.setDateOfBirth(10, 2, 3);
    
    //lets confirm by printing 
    std::cout << a.getDateOfBirth().getMonth() << "-" << a.getDateOfBirth().getDay() << "-" << a.getDateOfBirth().getYear() <<std::endl; 
    return 0;
}

Demo

The output of the above program is:

10-2-3
  • Related