简体   繁体   中英

C++ derived class calls method on base class before initialization

Here is a simple program, that I am pretty sure has undefined behavior, but I want to be certain.

struct A {
  int x;
  A(int y):x(y) {}
  int foo() { return x; }
};

struct B : public A {
  B():A(foo()) {}
};

I am assuming that this has undefined behavior because the call to A::foo occurs before the A object is constructed and it reads a class variable that is not initialized.

However, if the implementation of A::foo is changed to { return 0; } { return 0; } rather than { return x; } { return x; } , ie the function doesn't access the class members, is it still undefined behavior?

Further question - does anything change if A::foo is virtual ?

This is undefined behavior in both cases (including virtual member functions), as specified in class.base.init :

Member functions (including virtual member functions, [class.virtual]) can be called for an object under construction... However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the program has undefined behavior.

This bullet point contains essentially the example code snippet that you have provided, and explicitly points out the undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM