class X {
int i;
public:
X() { i = 0; }
void set(int ii) { i = ii; }
int read() const { return i; }
int permute() { return i = i * 47; }
};
Above is the definition of class X
Another class Y is there as
class Y : public X {
int i; // Different from X's i
public:
Y() { i = 0; }
int change() {
i = permute(); // Different name call
return i;
}
void set(int ii) {
i = ii;
X::set(ii); // Same-name function call
}
};
My doubt is that class X also consists of a variable named i and it is been inherited by class Y, but i of class Y should overwrite it, but the size of class(Y) is coming 8.
Secondly, for the line
X::set(ii)
Can we call the function like this?
Is this function of class X invoked for any object?
Many many thanks in advance
Y::idoesn’t override anything (you can only override a virtual function). It hidesX::i, so there are two differentis, one in the base class and one in the derived.To your second question, outside of the class you can only use syntax like
X::set(ii);whensetis astaticmember function, not a normal orvirtualmember function. Inside the class you can use it to force a particular class’ definition of the member function to be used.Edit: I should probably answer the tricky (somewhat related) question: if the static type differs from the dynamic type, which
iis used? For example, let’s consider a simplified version:Now, since
setis virtual, the call inmainis toderived::set. Sincehideis not virtual, the call inmainwill be tobase::hide(). The question is, which class’iwill each of them assign to?The answer is fairly simple: even when the function is virtual, the variable is not, so each function refers to the variable in its own class. Having/lacking
virtualcontrols which function you call, but not which variable is referred to by that function.