I'm trying to extend someone else's API for my own purposes, and I'm trying to get my head around class inheritance in that context.
I've written this minimal program:
#include
class first_class {
public:
first_class() {};
};
class second_class : first_class {
private:
int y;
public:
int get_y() { return y; }
second_class() {
y=99;
}
};
int main() {
first_class* a = new first_class();
second_class* b = new second_class();
int q = ((second_class*)a)->get_y();
printf("%d\n",q);
int r = b->get_y();
printf("%d\n",r);
}
first_class does nothing at all, and has no members. second_class inherits from first_class, but adds a private member y and a getter function, get_y();
When I call get_y() on an instance of second_class, it works as expected. When I call get_y() on instance of first_class, which I have cast to second_class, it returns 0.
Is that what should be expected? Are all child-class-only member variables automatically set to zero, or is that one of those usually-happens-but-not-actually-guaranteed things that compilers do sometimes, and they should actually be treated as undefined?