Calling a virtual function through a member-access expression

78 views Asked by At

I came acros the following rule N4296::12.7/4 [class.cdtor]:

If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

What does that mean? Couldn't you give an explanation of it with an example? It's a little bit hard to imagine that for me.

1

There are 1 answers

0
TheCppZoo On

In case you still want to know, this refers to when you are in the destructor of a base class and you refer to things of the the whole object that have already been destroyed. An example:

struct Derived;

struct Base {
    Derived &der;
    Base(Derived &d): der(d) {}
    ~Base();
};

struct Derived: Base {
    int value;
    Derived(): Base(*this) {}
};

#include <iostream>

Base::~Base() {
    std::cout <<
        der.value // this is the undefined behavior! der.value is *gone*
        << std::endl;
}

AFAIK, everything in that code is legal except accessing der.value in the destructor of Base because when you are destroying Base you've already destroyed the Derived you kept a reference of in der