News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ tips - Pure virtual member func, printing (FAQ 73 & 74)

Started by ben2ong2, October 07, 2006, 09:47:31 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

Q73: What is a `pure virtual' member function?

A: Some member functions exist in concept, but can't have any actual defn.  Ex:
Suppose I asked you to draw a Shape at location (x,y) that has size 7.2.  You'd
ask me `what kind of shape should I draw', since circles, squares, hexagons,
etc, are drawn differently.  In C++, we indicate the existence of the `draw()'
method, but we recognize it can only be defined in subclasses:

   class Shape {
   public:
     virtual void draw() const = 0;
     //...                     ^^^--- `=0' means it is `pure virtual'
   };

This pure virtual makes `Shape' an ABC.  The `const' says that invoking the
`draw()' method won't change the Shape object (ie: it won't move around on the
screen, change sizes, etc).  If you want, you can think of it as if the code
were at the NULL pointer.

Pure virtuals allow you to express the idea that any actual object created from
a [concrete] class derived from the ABC *will* have the indicated member fn,
but we simply don't have enough information to actually *define* it yet.  They
allow separation of interface from implementation, which ultimately allows
functionally equivalent subclasses to be produced that can `compete' in a free
market sense (a technical version of `market driven economics').


Q74: How can I provide printing for an entire hierarchy rooted at `class X'?

A: Provide a friend operator<< that calls a protected virtual function:

    class X {
    public:
      friend ostream& operator<< (ostream& o,const X& x)
        { x.print(o); return o; }
      //...
    protected:
      virtual void print(ostream& o) const;  //or `=0;' if `X' is abstract
    };

Now all subclasses of X merely provide their own `print(ostream&)const' member
function, and they all share the common `<<' operator.  Friends don't bind
dynamically, but this technique makes them *act* as if they were.


You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login