I have seen this question http://www.careercup.com/question?id=384062
class Base {
public :
virtual void method () = 0;
private :
int n;
};
void Base::method() { n = 1;}
class D1 : Base {};
class D2 : public D1 {
int i;
void method() {i = 2;}
};
It passed the compiler of vs2008 and g++ 4.4.3
Here is my understanding of above code, please correct me if I am wrong
S1> D1 has inherited variable Base::n but it cannot access it.
S2> D1 has inherited the function Base::method but it doesn’t call/modify this inherited function in the above implementation.
S3> D2::method is not an overridden version of D1::method
D1has inherited variableBase::nbut it cannot access it.Correct.
Private members of a class are never accessible from anywhere except the members of the same class.
D1has inherited the functionBase::methodbut it doesn’t call/modify this inherited function in the above implementation.Correct, but conditonally, Read below for why:
D1inherits theBase::methodbut it is not calling/invoking it because you did’nt add any statement to do so. But it can call it.Pure virtual functions can have a body and they can be called by drived class members just like any other member function.
Note that in your Base class
nis private so the only way to access it is through member function of Base & since onlymethod()can do so, You can do it through it.Note that presence of atleast one pure virtual function makes an class Abstract Class, And one cannot create objects of an Abstract class. Any class deriving from an Abstract class must override ALL the pure virtual functions of the Base class or else the derived class becomes an Abstract class as well.
Based on above rule,
In your case both
BaseandD1are Abstract classes.D2::methodis not an overridden version ofD1::methodIncorrect
Though
method()is not acessible to the ouside world through instance of classD1, it is still very much a part of it. Access control dictates access rights not presence or absence of members.So, Yes,
D2::methodis an overriden version ofD1::methodand it hides it as well, just that in this case,D1::methodwas not acccessible in the first place