///////////////////////////////////////////////////////////////////// // initialization.cpp - demonstrate initialization sequence // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2002 // ///////////////////////////////////////////////////////////////////// #include #include #include /////////////////////////////////////////////////////////////// // Base class declaration class Base { public: Base(const std::string &s); virtual ~Base() { } virtual void show(); private: std::string _name; }; //----< base constructor >------------------------------------- Base::Base(const std::string &name) : _name(name) { } //----< display member string >-------------------------------- void Base::show() { std::cout << "\n Base string = \"" << _name << "\""; } /////////////////////////////////////////////////////////////// // Derived class declaration class Derived : public Base { public: Derived(std::ostream &out, int size, const std::string &name); virtual void show(); private: std::ostream &_out; int _size; double *darray; }; //----< Derived constructor with initialization sequence >----- // // Note that: // - Base(name) is an explicit call to a Base constructor // - _out(out) is the only correct way to initialize this // class's reference member of type ostream // - size(size) simply initializes the value of this int member // - darray(new double[size]) allocates memory for the darray // pointer // Derived::Derived(std::ostream &out, int size, const std::string &name) : Base(name), _out(out), _size(size), darray(new double[size]) { if(darray == NULL) throw "memory allocation failure"; for(int i=0; i<_size; i++) darray[i] = (i+.5)*(i+.5); } //----< display Derived class state >-------------------------- // // Note that: // - Derived::show() uses Base::show() to display its internal // Base state. // - We could have made the Base::name member protected, rather // than private, but it is much better to let the Base class // handle its own activities // void Derived::show() { Base::show(); _out << "\n darray: "; for(int i=0; i<_size; i++) _out << std::setw(8) << darray[i]; _out << '\n'; } //----< demonstration entry point >---------------------------- void main() { Derived dTest(std::cout,5,"now is the hour"); dTest.show(); std::cout << "\n\n"; }