Cast of pointer to base to pointer to derived

Discussion in 'C++' started by braton@gmail.com, Aug 2, 2008.

  1. Guest

    Consider the following code:

    class A
    {
    public:
    void SpecialFun() {}
    };

    class B
    {
    public:
    static B* Create() { return new B(); }

    private:
    B() {}

    protected:
    A iA;
    };

    class C : public B
    {
    public:
    void InvokeSpecialFun() { iA.SpecialFun(); }
    };

    int main(void)
    {
    B* b = B::Create();
    /* <Legal?> */
    ((C*)b)->InvokeSpecialFun();
    /* </Legal?> */
    delete b;

    return 0;
    }

    In other words i need to invoke some function from the protected
    member of class B. So I derive from it into class C. Unfortunately,
    the constructor of B is private, I can only create the object using
    factory function. The question is can I cast the pointer that points
    to B such as described in the code provided that I am not adding any
    other members into C (the size of C shouldn't change after all). It
    works on some particular system but I'm interested what the standard
    says about it. If this is legal which of the C++ casts should I use
    here?

    Kind Regards
    , Aug 2, 2008
    #1
    1. Advertising

  2. Guest

    > Sure. The cast is legal. The behavior is undefined.

    Could you point out where exactly in the standard it is specified that
    the behavior is undefined?

    Thanks
    , Aug 2, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. tirath
    Replies:
    3
    Views:
    694
    Ivan Vecerina
    Oct 12, 2003
  2. Kavya
    Replies:
    2
    Views:
    367
  3. Replies:
    4
    Views:
    389
    Alf P. Steinbach
    May 23, 2007
  4. Replies:
    1
    Views:
    383
    myork
    May 23, 2007
  5. Replies:
    1
    Views:
    371
    Victor Bazarov
    May 23, 2007
Loading...

Share This Page