简体   繁体   中英

Can a base class sometimes initialize a derived class's member?

Does this program have well-defined behavior?

struct Foo;

struct FooImpl {
  FooImpl();
};

struct Foo : FooImpl {
  int bar;
};

FooImpl::FooImpl() {
  static_cast<Foo *>(this)->bar = 0;
}

int main() {
  return Foo().bar;
}

Of particular note is that Foo::bar is default initialized. I know this certainly is bad if Foo::bar gets initialized by Foo , hence this particular example.

Please keep in mind that this is a simplified example to illustrate a case. I'm interested in what the C++ spec has to say about this (and not whether or not this is good or bad code stylistically).

In general, parent can access children's members. Like the CRTP .

However, accessing them in destructors and constructors leads directly to UB.

 FooImpl::FooImpl() 
 {
    static_cast<Foo *>(this)->bar = 0;
 }

This is UB because Foo and subsequently bar have not been constructed yet and you already access it (and modify it.). Similarly in destructor - bar would already be deleted by this point. Instead you could create Initialize() method in FooImpl with the same body and call it in Foo 's constructor then it would be legal.

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