CS253

CS253: Software Development with C++

Spring 2018

Member Initialization

See this page as a slide show

Member Initialization

CS253 Member Initialization

The Old Way

class Name {
  public:
    Name() { first="John"; last="Doe"; }
    Name(string f) { first=f; last="Doe"; }
    Name(string f, string l) { first=f; last=l; }
    string full() const { return first + " " + last; }

  private:
    string first, last;
};

Name a, b("Cher"), c("Barack", "Obama");
cout << a.full() << '\n' << b.full() << '\n'
     << c.full() << '\n';
John Doe
Cher Doe
Barack Obama

Member Initialization

Member initialization:

class Name {
  public:
    Name() : first("John"), last("Doe") { }
    Name(string f) : first(f), last("Doe") { }
    Name(string f, string l) : first(f), last(l) { }
    string full() const { return first + " " + last; }

  private:
    string first, last;
};

Name a, b("Cher"), c("Barack", "Obama");
cout << a.full() << '\n' << b.full() << '\n'
     << c.full() << '\n';
John Doe
Cher Doe
Barack Obama

Delegation

BAD!

class Name {
  public:
    Name() { Name("John", "Doe"); }
    Name(string f) { Name(f, "Doe"); }
    Name(string f, string l) : first(f), last(l) { }
    string full() const { return first + " " + last; }

  private:
    string first, last;
};

Name a, b("Cher"), c("Barack", "Obama");
cout << a.full() << '\n' << b.full() << '\n'
     << c.full() << '\n';
 
 
Barack Obama

Delegation

Good:

class Name {
  public:
    Name() : Name("John", "Doe") { }
    Name(string f) : Name(f, "Doe") {}
    Name(string f, string l) : first(f), last(l) { }
    string full() const { return first + " " + last; }

  private:
    string first, last;
};

Name a, b("Cher"), c("Barack", "Obama");
cout << a.full() << '\n' << b.full() << '\n'
     << c.full() << '\n';
John Doe
Cher Doe
Barack Obama

Details

Modified: 2018-02-09T12:21

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building