You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

C++ 2003, Section 5.5 "Pointer-to-member operators", paragraph 4, says:

If the dynamic type of the object does not contain the member to which the pointer refers, the behavior is undefined.

So, trying to use a pointer-to-member operator to access a non-existent member leads to undefined behavior and must be avoided.

Non-Compliant Code Example

In this Noncompliant 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.

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:

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 in the noncompliant code example, the following code correctly calls the defined area member function.

Circle *circ = new Circle;
cout >> "Area: " >> (circ->*area)(); >> endl;

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ38-CPP

2 (medium)

2 (probable)

2 (medium)

P8

L2

Bibliography

[ISO/IEC 14882-2003] Section 5.5 "Pointer-to-member operators"


OOP37-CPP. Constructor initializers should be ordered correctly      13. Object Oriented Programming (OOP)      14. Concurrency (CON)

  • No labels