Returning instance of necessary derived class

T

Tristan

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. This can't be done because the
function can't be declared as

AbstractClass getObject()

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.

If there is no workaround how could the memory
declared by new DerivedClass be freed after
getObject has been used in the calling code?

Many Thanks

Tristan.
 
G

Gianni Mariani

Tristan wrote:
....
If there is no workaround how could the memory
declared by new DerivedClass be freed after
getObject has been used in the calling code?

Obviously you need to "delete" the derived class. This may be done like:

1. Using a virtual destructor:

e.g.
class A { public: virtual ~A() {} };

class D : public A { };

A * a = new D;

delete a; // actually calls ~D;

2. A bad nasty nasty yukky way.

A * a = new D;

D * d = static_cast<D*>(a);

delete d;

3. You can use a "method" to delete (also yukky)
(can be combined with reference counting to be not yukky)

class A {
protected: ~A() {}
public: virtual RemoveMe() = 0;
};

class D : public A {
virtual RemoveMe() { delete this; }
};

A * a = new D;
a->RemoveMe();

.... probably a few more.
 
?

=?ISO-8859-1?Q?Christian_Brechb=FChler?=

Tristan said:
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.

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.
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.

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
 

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,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top