| re: Returning instance of necessary derived class
Tristan wrote:[color=blue]
> I have a function:
>
> AbstractClass* getObject()
> {
> AbstractClass* d = new DerivedClass;
>
> return d;
> }
>
> What I want is for this function to return an
> actual instance of the derived class not a
> pointer to it.[/color]
Why do you want that? Can you post a sample of ideal code using your class?
The reason I ask is that if you return an object (rather than a pointer
or reference) into code that doesn't know the exact type, you get
slicing (see 12.2.3). Which is almost certainly not what you want.
[color=blue]
> Inside this function I will be declaring the derived
> type based on a code read from a file which is
> why the correct object must be created and returned.[/color]
I assume you mean that getObject does something like this,
AbstractClass* getObject()
{
int code;
in_stream >> code;
if (code = 42)
return new DerivedClassA();
else
return new DerivedClassB();
}
You seem interested in runtime polymorphism, which you only get if you
manipulate objects through pointers and references (see 12.2.6).
Christian |