0

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();

}
7
  • 2
    Note: overloading != overriding! Commented Aug 12, 2022 at 11:46
  • you are missing a virtual destructor. Parent* p = new Child(1,2,3); delete p; wont work Commented Aug 12, 2022 at 11:47
  • 1
    btw "(in this case an interface)". In C++ "interface" is not a formal term, but usually an interface has no members, only pure virtual methods (and a virtual destructor) Commented Aug 12, 2022 at 11:49
  • This question can't be answered in competent way since we do now know what this code should be doing. And context is very important. For example is highly probable that inheritance here should not be used (in this way). Note symbol names are not vary helpful here: Parent Child says nothing about class responsibility (it describe relations, which is not helpful), also when I see merge I expect argument what should be merged. Commented Aug 12, 2022 at 11:52
  • @463035818_is_not_a_number exactly, freeing the 'heap' memory was missing. Thanks! Commented Aug 12, 2022 at 11:53

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.