Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling virtual function from member constructor

Tags:

c++

I'm curious as to the behaviour of the following:

#include <iostream>
#include <string>
struct A;
struct B {
    std::string b;
    B(A& a);
};
struct A {
    B member;
    virtual std::string f() { return "Hello, World!"; }
    A() : member(*this) {}
};
B::B(A& a) : b(a.f()) {}
int main() {
    std::cout << A().member.b;
}

Is this required to print the expected result? Or is it undefined behaviour?

like image 248
Puppy Avatar asked Sep 08 '14 11:09

Puppy


1 Answers

This is legal. §12.7 [class.cdtor]/p4:

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not one overriding it in a more-derived class. 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.

The UB case doesn't apply here.

like image 63
T.C. Avatar answered Sep 27 '22 01:09

T.C.