lundi 14 mai 2018

Preferred way to initialize base class members (c++)

I have a base class:

class Base {
protected:
    int m_a;
    virtual void foo() = 0;
}

And a derived class(es)

class Derived : public Base {
public:
    Derived(int a);
}

The base class is abstract, so only derived classes can be created. How is the better way to implement the derived Ctor?

Derived::Derived(int a) : Base(a) {}
Base::Base(int a) : m_a(a) {}

Or

Derived::Derived(int a) { m_a = a;}
Base::Base(){}

Is it better to remove the member from Base constructor, since it cannot be created alone, OR to keep it on the Base constructor to stay the assignment for him?

Aucun commentaire:

Enregistrer un commentaire