valid syntax?

A

Anonymous

I implementing the 'virtual constructor' idiom, I have a retrieve()
method on an interface, which retrieves an object from storage.

I am using this line to cast "up":


MyObject::retrieve()
{
Base * base = Create(object_id) ;
*this = *dynamic_cast<MyObject*>(base) ; //<- this line
...
}

Notes:
i). MyObject derives from Base
ii). Create is a virtual constructor which returns ptr to objects
derived from Base
 
J

Jonathan Lane

I think the syntax here is valid but might not be what you want.
Dereferencing this and the result of the dynamic cast will invoke the
operator=() on MyObject. If you haven't implemented that then it will
do a bitwise copy. If you meant for this to point to the newly created
object then you want to get rid of 2 asterisks on that line.

Bear in mind as well that dynamic cast can fail. When dynamic casting
pointers a failure will return NULL which you'll then try to
dereference and consequently crash.

Why do you ask if it's valid syntax? What does the compiler say?
 

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

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,647
Latest member
NelleMacy9

Latest Threads

Top