POV-Ray : Newsgroups : povray.programming : C++ inheritance puzzler : Re: C++ inheritance puzzler Server Time
19 Apr 2024 18:24:37 EDT (-0400)
  Re: C++ inheritance puzzler  
From: Warp
Date: 27 Nov 2010 15:27:00
Message: <4cf16993@news.povray.org>
Le_Forgeron <jgr### [at] freefr> wrote:
> (2) is not allowed because a() of A is protected, so can only be called
> by the object itself (in a gross simplification).

  Actually that's not completely true. This is completely ok:

class A
{
 protected:
    void protectedFunctionOfA() {}
};

class B : public A
{
 public:
    void foo(B* other)
    {
        other->protectedFunctionOfA(); // ok
    }
};

  'protectedFunctionOfA()' is not being called by the object itself, yet
it's ok. However, the difference is that 'other' is of type B, in which
case it's allowed. However, if it was of type A, it would not be allowed:

    void foo(A* other)
    {
        other->protectedFunctionOfA(); // not ok
    }

  Basically, B is allowed to call the function only if the object is
(known to be) of type B, but not if it's only known to be of type A
(by static typing, ie. even if the object behind the pointer is in
reality of type B).

  Even if you did this, you would still get an error:

void B::foo()
{
    A* ptr = this;
    ptr->protectedFunctionOfA(); // not ok
}

  (The compiler *could* deduce in this case that 'ptr' is really pointing
to an object of type B, but there are only so many cases where it could
prove it for certain, and this could change from compiler to compiler.)

  Needless to say, gcc (and probably most other C++ compilers) will give
an error for that, so it just cannot be done. If you need to call the
protected section of the object, take a pointer of the derived type,
because that's what it has to be.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.