Is there a way to make a "virtual" variable in a C++ base class?

Viewed 1050

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?

5 Answers
Related