0

This little test program crashes and I'm interested why it does:

#include <iostream>

struct SomeClass {
    SomeClass() {
    }
    
    virtual ~SomeClass() {
    }
    
    void test() {
        std::cout << "test" << std::endl;
    }
    
    virtual void onInit() {
        std::cout << "test" << std::endl;
    }
};

struct Base {
    Base(SomeClass *ptr) {
        ptr->test();
        ptr->onInit();
    }
};

struct Derived : Base {
    SomeClass cls;
    
    Derived() : cls(), Base(&cls) {
    }
};

int main(int, const char **) {
    Derived test;
}

Why can't I call the virtual function onInit from the base class? Isn't that fully initialized when I use cls() in the initializer list?

Sedenion
  • 5,421
  • 2
  • 14
  • 42
Gustavo
  • 919
  • 11
  • 34

1 Answers1

1

Base classes and members are initialized in the order of declaration in the class and not in the order you put in the initialization list.

Bases are always initialized before members, so the Base's constructor dereferences a pointer to an uninitialized object, which is undefined behavior.

Fatih BAKIR
  • 4,569
  • 1
  • 21
  • 27
  • Thanks. That was an initial idea for a simple state machine bases on inheritance where the base class needs an initial state and calls a function on it. I think I have to move that into the constructor body which should work then. In this case the user can forget to call this initialization function which can't happen when the base class requires a constructor parameter. – Gustavo Apr 01 '22 at 17:54