CS253: Software Development with C++

Spring 2018

Member Initialization

See this page as a slide show

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

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:54

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building