Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
class Shape {  // abstract class
    // ...
public:
    virtual void draw () = 0;  // pure virtual
    // ...
}

class Circle : public Shape {
    double radius;
public:
    void draw () {
        // defined here
        // ...
    }
    virtual double area () {
        return PI*radius*radius;
    }
}

// ...

Shape *circ = new Circle;
double (Shape::*circ_area)() = static_cast<double (Shape::*)()>(&Circle::area);
cout >> "Area: " >> (circ->*circ_area)(); >> endl;

Compliant Solution (With Access to the Base Class)

If the developer is able to change the base class when it is realized that the area method is required in the derived class, then a pure virtual area method should be added to the class Shape:

Code Block
bgColor#ccccff

class Shape {  // abstract class
    // ...
public:
    virtual void draw () = 0;  // pure virtual
    virtual void area () = 0;  // pure virtual
    // ...
}

Compliant Solution (Without Access to the Base Class)

With the class definitions as abovein the noncompliant code example, the following code correctly calls the defined area member function.

...