Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

oop

c++11

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?

like image 972
jackcogdill Avatar asked Jan 01 '14 19:01

jackcogdill


1 Answers

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) {}
};
like image 166
Jarod42 Avatar answered Nov 20 '22 08:11

Jarod42