I have a virtual class A with data val and val2. val is set by A, but val2 is supposed to be set by children of A (based on the value of val). I would like to force every deriving class to set val2. The following
#include<iostream>
class A {
public:
A(): val(1), val2(getVal2())
{};
int val;
int val2;
protected:
virtual int getVal2() = 0;
};
class B: public A {
protected:
virtual int getVal2() { return 2*val; };
};
int main(){
B b;
std::cout << b.val2 << std::endl;
}
does not work since the constructor of A calls a function (getVal2) which at the time isn't defined yet:
/tmp/cc7x20z3.o: In function `A::A()':
test9.cpp:(.text._ZN1AC2Ev[_ZN1AC5Ev]+0x1f): undefined reference to `A::getVal2()'
collect2: error: ld returned 1 exit status
What's a better way of forcing deriving classes to set val2 explicitly?