'Call virtual function on derived member variable [duplicate]

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?



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fatih BAKIR