Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens for virtual function that is non-public inherited by subclass?

Tags:

c++

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

like image 830
q0987 Avatar asked Nov 18 '25 09:11

q0987


1 Answers

S2 and S3 are wrong.

D1's methods can call it's Base::method(), but other code can't as Base part of D1 is private.

Base::method() is overridden by D2. If you somehow convert (new D2) to (Base*) and call Base::method, the i=2 code will run.

Considering access control, if you have pointer to Base*, external code can use ->method() because it's public, and if you have pointer to D2*, ->method() can't be called because it's private, even if it's the same object and the same method.

Also, despite your (n=1) implementation for Base::method() it and its class remain abstract.

like image 199
hamstergene Avatar answered Nov 19 '25 23:11

hamstergene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!