mardi 19 juillet 2016

Requiring "public" access modifier when using instance in auto scope

Suppose we have two classes, one derived from other and it contains only one virtual non-pure method like this:

class Base
{
public:
    virtual void method()
    {
        cout << "method() called from Base" << endl;
    }
};


class Derived : public Base
{
public:
    void method()
    {
        cout << "method() called from Derived" << endl;
    }
};


int main()
{
    Base *instance1 = new Derived();
    instance1->method();

    Derived derived;
    derived.method();
}

Why, if we do not specify explicitly "public" access modifier in Derived class (so, compiler assumes that it's private) it wouldn't compile? Why instantiation way(via pointer and via regular variable) does affect to the visibility scope? Is there any rationale regarding this behavior?

Many thanks!

Aucun commentaire:

Enregistrer un commentaire