Jump to content
  • Advertisement
Sign in to follow this  
Evil Steve

Is this valid C++...

This topic is 4323 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

...Or do I have yet another reason to hate CodeWarrior?
class Base
{
protected:
   bool isFoo() {return true;}
};

class Derived : public Base
{
public:
   void foo()
   {
      Base* pOther = new Derived;
      pOther->isFoo(); // This line...
   }
};

Is that valid C++? If I change this line: Base* pOther = new Derived; to: Derived* pOther = new Derived; Then it compiles ok. Othersise I get:
Quote:
Error: illegal access from 'Base' to protected/private member 'Base::isFoo()' pOther->isFoo(); // This line...

Share this post


Link to post
Share on other sites
Advertisement
'protected' only allows derived objects access. In the case where "pOther" is a "Base" pointer the static type at the call point is "Base" and so access is not granted, even though it's the same dynamic type. The compiler only evaluates the static type, i.e. what the object is declared as. Defining "pOther" as a Derived type means the static type at the call point is now "Dynamic" and so the access is allowed. Does that make sense?

Skizz

Share this post


Link to post
Share on other sites
It's not valid. A protected member can be accessed by methods or friends of a derived class through an object, reference or pointer of that derived class. Pointers of the base class may not be used for access.

In practice, making a member protected in class Base makes it accessible as if it were a private member of class Derived and class Base: you cannot access Base::foo without being a friend of Base, but you can access Derived::foo (which is in fact the same thing) if you are a friend of Derived. Of course, to access it, you need an object/reference/pointer of type Derived in the first place.

Share this post


Link to post
Share on other sites
Your code is invalid.

If it wasn't, then your class Derived could fiddle with the protected variables of any class derived from Base.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!