I know there is no late binding for class attributes. But i need a good pattern to do this:
#include <cstdlib>
#include <iostream>
using namespace std;
class B
{
public:
const int i;
B() : i(1) {}
};
class D : public B
{
public:
const int i;
D() : i(2) {}
};
int main()
{
D d;
B *ptr = &d;
cout << ptr->i << endl;
return 0;
}
Output is 1, but I expected 2. I guess, i should use a different pattern. Any suggestion?
The version of
ithat gets output is dependent on the compile-time type definition. You’ve defined two different variables, so you’ll get two different results. The way to fix this is to make sure there’s only one version of the variable. You can use a contructor in B to initialize the const variable.