I have this code, note that two lines have been commented out
#include <iostream>
class foo {
public:
foo();
int i;
};
class bar: foo {
public:
bar();
//int i;
};
foo::foo()
{
i = 2;
}
bar::bar()
{
i = 4;
}
int main()
{
bar *b = new(bar);
//std::cout << "bi = " << b->i << std::endl; /*line 28*/
foo *f = (foo*) b;
std::cout << "fi = " << f->i << std::endl;
}
With the two lines commented out, the code compiles and the output is
fi = 4
With the two lines uncommented, the code compiles and the output is
bi = 4
fi = 2
With only the declaration of i within class bar commented out the compilation fails
var.cc: In function ‘int main()’:
var.cc:6:7: error: ‘int foo::i’ is inaccessible
var.cc:28:30: error: within this context
I understand the first two cases but I do not understand this compilation error. Why is
the variable "i" accessible from within the bar constructor but not from a bar pointer?