Home > Back-end >  C best practice for overloading inherited class
C best practice for overloading inherited class

Time:08-12

Is this the proper (best) way to initialize both the constructor of the parent class (in this case an interface) and the constructor of the child class?

class Parent {
protected:
    int x, y;
private:
    int pvt = 2;
public:
    int pub = 3;

    Parent(int n1, int n2)
        : x(n1), y(n2) {}

    virtual void merge_parent() {
        std::cout << "[parent]: " << x << y << pvt << pub << std::endl;
    }

    virtual void merge() = 0;
};


class Child : public Parent {
private:
    int c;
public:
    Child(int n1, int n2, int n3): Parent(n1, n2), c(n3) {}

    void merge() override {
        std::cout << "[child]: " << x << y << c << pub << std::endl;
    }
};


int main() {

    Child* p = new Child(1, 2, 3);
    p->merge_parent();
    p->merge();

}

CodePudding user response:

Yeah looks good. You used parent constructor for the child constructor which is the proper way in the case child looks like marent with some new private members. It is also what I uasually do from experience.

CodePudding user response:

Everything looks OK, EXCEPT you need to declare a virtual destructor in your base class.

class Parent { 
public:
    virtual ~Parent() = default;
};

If you do not do this the destructor in your derived class will not be called when attempting to delete a pointer of type Parent.

Parent* parent = new Child{1, 2, 3};
// The destructor in the derived class 'Child' will not be called
// unless you declare a virtual destructor in your base (Parent) class.
delete parent;
  • Related