Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tested code

...

Non-Compliant Code Example

In this Noncompliant Code Example non-compliant code example there is an abstract base class Shape and a derived class Circle that
contains a member function area. The last line of the code following the class definitions results in undefined behavior because there is no member function corresponding to area() in the class Shape.

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

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

// ...

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

Compliant Solution (

...

Modifiable 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 (

...

Non-modifiable Base Class)

With In many cases, the class definitions as in the noncompliant code example, the following code correctly calls the defined area member functionbase class is not modifiable. In this case, one must call the derived method directly.

Code Block
bgColor#ccccff
Circle *circ = new Circle(2.0);
cout >><< "Area: " >><< (circ->*area>area)(); >><< endl;

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ38-CPP

2 (medium)

2 (probable)

Medium

Probable

Medium 2 (medium)

P8

L2

Bibliography

Wiki Markup
\[[ISO/IEC 14882-2003|AA. Bibliography#ISO/IEC 14882-2003]\] Section 5.5 "Pointer-to-member operators"

...