How does the standard support this pure virtual function call in the base S class?

Consider this snippet:

#include <iostream>
struct S {
    virtual void pure1() = 0;
    virtual void pure2() = 0;
};

struct T : S {
    void pure1() { std::cout << "T::pure1" << '\n'; }
    void pure2() { std::cout << "T::pure2" << '\n'; }
};


void S::pure2() { std::cout << "S::pure2" << '\n';}

int main()
{
    T t;
    t.S::pure2();
}

      

He is typing S::pure2

.

Looking at the C ++ 11 standard, I don't know exactly how this happens. I believe this is related to ยง3.4.5 / 4:

If id-expression in class member access is qualified identifier form

class name or namespace-name :: ...

class name or namespace name following. or โ†’ operator is first looked up in the object expression class and name, if found, is used. Otherwise, it is considered in the context of the entire postfix expression.

But I don't understand how the pure virtual function pure2()

is in the base class S

with the t.S::pure2();

above expression .

+3


source to share


2 answers


This is ok for a pure virtual function to be implemented in the base class. The standard states that this is valid (emphasis mine):

10.4 Abstract classes

2 An abstract class is a class that can only be used as the base class of another class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [Note: such a function can be inherited: see below. -end note] The virtual function is specified pure using pure-specifier (9.2) in the function declaration. A pure virtual function should only be defined when called with, or, as if with (12.4), with the qualified identifier syntax (5.1).

If you didn't call



t.S::pure2();

      

then it will be ok to omit the implementation S::pure2()

. It will be a link time error if you didn't implement S::pure2()

but still called

t.S::pure2();

      

+5


source


The bit you are citing covers searching S

in an expression t.S::pure2()

. It has nothing to do with the name at all pure2

.

The relevant regulation is here 10.3 / 15:



Explicit qualification with the scope operator (5.1) suppresses the virtual calling mechanism. [Example:

class B { public: virtual void f(); };
class D : public B { public: void f(); };
void D::f() { /* ... */ B::f(); }

      

Here, the function call in D::f

really calls B::f

, not D::f

. -end example]

+2


source







All Articles