Tirafesi
Tirafesi

Reputation: 1479

Segmentation fault in constructor initialization list

I have an abstract class MyClass that has a const attribute my_attr. Each subclass should initialize this attribute as they see fit, by overriding the pure virtual method init_my_attr.

The problem is that this results in a segmentation fault.

// MyClass.h

class MyClass : public MyParentClass
{
public:
    MyClass(...);

protected:
    virtual vector<int> init_my_attr() const = 0;

private:
    const vector<int> my_attr;
}


// MyClass.cpp

MyClass::MyClass(...) : MyParentClass(...), my_attr(this->init_my_attr())
{

}

What's wrong with the above code?

Upvotes: 0

Views: 223

Answers (1)

NathanOliver
NathanOliver

Reputation: 180720

You can't call a virtual function in the constructor. Base classes are constructed first so there is no derived class that you can call the virtual function on.

That said, there is a really easy solution. Add a constructor to MyClass that takes a std::vector and initializes my_attr with it. Then your derived class can call that constructor and pass it a vector that it created.

Upvotes: 7

Related Questions