C++: Access protected virtual member function via a base class

Marco Man-Fai Yu yumf@chasingwind.com
Thu May 25 00:13:00 GMT 2000


Hi,

    I'm using g++ 2.95.1 on i686-pc-linux-gnu. It also fails on
Solaris 2.6 and the web compile at www.codesourcery.com.

g++ prints the following error when compiling the following code.

foo.cc: In method `void Derived::Do()':
foo.cc:8: `void Base::Do()' is protected
foo.cc:24: within this context

===== Code =====

class Base
{
protected:
    virtual void Do();
};

void Base::Do()
{
}

class Derived : public Base
{
protected:
    virtual void Do();
};

void Derived::Do()
{
    Do();             // Access my own Do(), ok
    Base::Do();       // Access my base's Do(), ok.
    Derived* q = new Derived();
    q->Do();          // Access another Derived's Do(), ok.
    Base* p = q;      // Same object via ptr to Base.
    p->Do();          // Access another Derived's Do() via
                      // Base ptr, not ok.
    delete q;
}

int main (int argc, char* argv[])
{
}



Is this a bug in g++? I think it is legal to access protected member
functions of my base class, even if it is another instantiation,
according to Stroustrup and other C++ books.

Thank you very much for your time,

Marco Yu


More information about the Gcc-bugs mailing list