I have a base class with a pointer that needs to get initialized specifically in the constructor of all sub classes. How can I ensure that this variable gets initialized in the subclasses' constructors? I essentially want the same functionality as making a pure virtual function, except with a pointer to an object. Is there a way to do that?
My code looks something like this:
A.hpp:
class A {
protected:
A();
X *pointer;
};
B.hpp:
class B : public A {
public:
B();
};
B.cpp:
B::B() : A() {
// how do i make sure pointer gets initialized here?
}
Is there a way to achieve this?
Change constructor of base class:
class A {
protected:
explicit A(X* pointer);
X *pointer;
};
And so child have to give value, as:
class B : public A {
public:
B() : A(nullptr) {}
explicit B(X* x) : A(x) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With