Artur Pyszczuk
Artur Pyszczuk

Reputation: 1930

Using pointer to member function of a base class on object of derived class

Consider following code snippet:

struct Base {
    std::string foo () const { std::cout << "Base::foo()\n"; return "X"; }
};

struct Der : Base {};

struct Ptr : std::integral_constant<std::string (Base:: *) () const, &Base::foo> {};

and usage is like this:

Der der;
std::string s = (der.*Ptr::value) ();
std::cout << s << "\n";

Output is as desired:

Base::foo()
X

Everything seems to be fine.

My question is: Is this code correct? Or am I stepping on the land of undefined behavior? Can I use pointer to member function of a base class on object of derived class directly?

Upvotes: 3

Views: 50

Answers (1)

skypjack
skypjack

Reputation: 50540

Roughly speaking, the member belongs to the suboject and thus you must use its type to identify it. Perfectly fine indeed.

The other way around doesn't even compile actually:

struct Ptr : std::integral_constant<std::string (Der:: *) () const, &Der::foo> {};

The error is pretty clear:

error: could not convert template argument '&Base::foo' from '[...] (Base::)() const}' to '[...] (Der::)() const'

Where I used [...] to reduce it a bit.

Upvotes: 3

Related Questions