Cast of pointer to base to pointer to derived

B

braton

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
 
B

braton

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top