// class examples of using initializer lists and inheritance #include #include #include #include using namespace std; // this class need to have an initializer list for the constructor because one // instance variable is a reference (out) and one is declared to be const (id). class foo { public: foo(ostream & o, const string & the_id, int n) : out(o), id(the_id), y(x - 1), z(x + 1), x(2 * n) { // nothing else to do } void print() const { out << "x = " << x << ", y = " << y << ", z = " << z << endl; } private: ostream & out; const string id; int y, x, z; // y will not be initialized properly because of order }; // base class for inheritance class person { public: person(const string & s, const string & n) : ssn(s), name(n) { // nothing else to do } const string get_name() const { return name; } // had to declare this function to be virtual to get polymorphic behavior virtual string to_string() const { ostringstream out; out << ssn << ", " << name; return out.str(); } private: string ssn; string name; }; // this is a subclass of person that adds a gpa instance variable class student : public person { public: student(const string & s, const string & n, double g) : person(s, n), gpa(g) { // nothing else to do } string to_string() const { ostringstream out; out << person::to_string() << ", " << gpa; return out.str(); } private: double gpa; }; int main() { foo f(cout, "879342782", 42); f.print(); cout << endl; person p1("833-28-2938", "John Doe"); student s1("837-99-2343", "Jane Smith", 3.95); cout << p1.to_string() << endl; cout << s1.to_string() << endl; cout << endl; // polymorphism person & p2 = s1; cout << p2.to_string() << endl; cout << endl; // example of "slicing" (a BIG problem) vector v; v.push_back(p1); v.push_back(p2); for (const person & p : v) { cout << p.to_string() << endl; } return 0; }