Link to home
Start Free TrialLog in
Avatar of dito
dito

asked on

virtual function?

for a project that I am developing, a friend told me to use 'pure virtual' functions in my classes. I am a beginner to C++ and hace no clue what she meant.
this project is due on Tuesday, so please answer fast!
ASKER CERTIFIED SOLUTION
Avatar of MaDdUCK
MaDdUCK

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MaDdUCK
MaDdUCK

A member function declaration that turns a normal class into an abstract class (i.e., an ABC). You normally only implement it in a derived class.

Some member functions exist in concept; they don't have any reasonable definition. E.g., suppose I asked you to draw a Shape at location (x,y) that has size 7. You'd ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc, are drawn differently). In C++, we must indicate the existence of the draw() member function (so users can call it when they have a Shape* or a Shape&), but we recognize it can (logically) be defined only in subclasses:

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

This pure virtual function makes Shape an ABC. If you want, you can think of the "= 0;" syntax as if the code were at the NULL pointer. Thus Shape promises a service to its users, yet Shape isn't able to provide any code to fulfill that promise. This forces any actual object created from a [concrete] class derived from Shape to have the indicated member function, even though the base class doesn't have enough information to actually define it yet.

Note that it is possible to provide a definition for a pure virtual function, but this usually confuses novices and is best avoided until later.

hope this helps,
MaDdUCK