CompuServe Messages

#Lattice C++

    03-Feb-90 22:35:30
Sb: #88399-#Lattice C++
Fm: Dave Love 75126,2223
To: Steve Ahlstrom 76703,2006
[ continuation ] 4. Derived classes and virtual functions C++ allows you to define new classes based upon other classes (very similar to wrapping structures around other structures (like MsgPort and Node)). The new "derived" class inherits all the properities of the base class. Further, if the base class contains functions declared as "virtual", the derived class can override them, if it needs to. Consider the following example: class object { // These two slashes denote a C++ comment protected: // The following elements are for internal use only object* next; public: // Anyone can access the following elements int x_pos, y_pos; char* name; object(char* name = NULL, int x = 0, int y = 0); // Constructor ~object(); // destructor virtual void draw(); // This function can be overridden by derived classes virtual void move(); void fill(); } Note that C++ allows functions to have default values, so the constructor above could legally be called with zero, one, two or three parameters. Now I could define a few specific objects as follows: class square : public object { // square is "derived" from the base class object int width; square(int width = 1); ~square(); void draw(); // and square will have its own draw routine void move(); } class circle : public object { // just another object int diameter; circle(int diameter = 0); ~circle(); void draw(); void move(); } Now, suppose you have a linked-list of objects (or classes derived from objects) and you want to draw them. The following code will do it: for (object* o = list; o; o = o->next) o->draw(); Circles would call the draw routine defined in the circle class, while squares call the draw routine defined in the square class. Also, notice that C++ allows you to declare variables where they make sense: the object pointer o is declared in the for() statement and is only defined within that statement. Well, now that you understand all that… 🙂 Actually I'll be happy if only a portion of it makes sense. C++ is a very powerful language, and I've only