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:
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
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
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