/** * CSE 374 Example * muh * more syntax for C++ classes */ #include using namespace std; // for the iostream stuff. class Rectangle { int length; int width; public: // constructor Rectangle (); //default Rectangle (int l, int w); // destructor virtual ~Rectangle () {}; int getArea(); }; // this is really simple, so we are just going to initialize // this syntax with the colon is to initialize values before the // construction. Its used with constructors. You can set const // member variables this way. Rectangle::Rectangle() : length(1), width(2) { cout << "Default constructor" << endl; } Rectangle::Rectangle(int l, int w) : length(l), width(w) {} int Rectangle::getArea() { return length*width; } class Square : public Rectangle { public: Square(); // default Square(int s); // constructor virtual ~Square(); // destructor }; // Here we are using the initialization syntax to call the // constructor of the Base class. Square::Square () :Rectangle (2,2) {} Square::Square (int s) :Rectangle (s,s) {} Square::~Square() { cout << "Destructing Square" << endl; } int main () { cout << "Make a couple of rectangles" << endl; Rectangle r1; // calls default constructor Rectangle r2(3,4); cout << "Areas of r1: " << r1.getArea() << endl; cout << "Areas of r2: " << r2.getArea() << endl; // can't do this because default access is private: // cout << "Rectangle members: " << r1.length << endl; cout << "Make a couple of squaress" << endl; Square s1; // calls default constructor Square s2(4); cout << "Areas of s1: " << s1.getArea() << endl; cout << "Areas of s2: " << s2.getArea() << endl; }