Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Cast of pointer to base to pointer to derived

Reply
Thread Tools

Cast of pointer to base to pointer to derived

 
 
braton@gmail.com
Guest
Posts: n/a
 
      08-02-2008
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
 
Reply With Quote
 
 
 
 
braton@gmail.com
Guest
Posts: n/a
 
      08-02-2008
> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 01:44 PM
Derived::Derived(const Base&) developereo@hotmail.com C++ 4 05-23-2007 09:32 AM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 12:07 AM
confusion involving pointer to pointer when converting from derived to base Kavya C++ 2 12-23-2006 07:31 PM
[RTTI] cast base class pointer to <templated> derived class pointer tirath C++ 3 10-12-2003 01:44 PM



Advertisments