By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,417 Members | 1,825 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,417 IT Pros & Developers. It's quick & easy.

Return pointer to object of common base

P: n/a
Classes B, C, D and E are derived from base class A.

A* CreateB();
A* CreateC();
A* CreateD();
A* CreateE();

class X
{
public:
A* ObtainA();
};

int main()
{
Xx;
A* p = x.ObtainA();
}

ObtainA() could return A pointer pointing either to B, or C, or D, or E.

How to code this so to tell Create() return B, or C, or D, or E at run-time?

Thanks!
Jul 22 '05 #1
Share this Question
Share on Google+
6 Replies


P: n/a
On Tue, 29 Jun 2004 07:35:42 GMT, "Busin" <bu****@fidrep.com> wrote:
Classes B, C, D and E are derived from base class A.

A* CreateB();
A* CreateC();
A* CreateD();
A* CreateE();

class X
{
public:
A* ObtainA();
};

int main()
{
Xx;
A* p = x.ObtainA();
}

ObtainA() could return A pointer pointing either to B, or C, or D, or E.

How to code this so to tell Create() return B, or C, or D, or E at run-time?

Thanks!


You could implement the Create function as a member function of the
base class which you can override in the derived classes, or you could
have a factory class which "knows" about all the different derived
types.

If you take the first path, you need an object before you can create
(e.g. clone) another one. With the factory design, you need a
parameter (or something) to tell your factory class what kind of
object to create. Typically, this is stored in application setup data
or gathered at run time from the user and passed directly to the
factory so that the application code using the object need not bother
about the object's actual type.

You could also use a template Create function, but it wouldn't be as
easy to separate knowledge about the different types from your
application code logic. However, if you need to have different objects
depending on int, double, etc. then this might be the way to go.
Again, you could possibly hide this in your factory class.

I am sure there are other ways. These are just a few ideas.

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #2

P: n/a

"Busin" <bu****@fidrep.com> wrote in message
news:iZ********************@bgtnsc04-news.ops.worldnet.att.net...
[SNIP]
ObtainA() could return A pointer pointing either to B, or C, or D, or E.

How to code this so to tell Create() return B, or C, or D, or E at run-time?
Thanks!


As Bob already pointed out there are different ways to tackle this problem,
but run-time specific object creation is commonly solved by a factory. This
means that in principle youīve got a number of classes derived from a common
base which all have a Create function. This function for the different
classes is registered with a factory and if you want to create an object of
a specific type you simply call up the factory with a specifier (e.g. class
name or whatever) which will return the appropriate object. This is a very
generic pattern and hence can be implemented via templates. For example:
// The factory
// simplefactory.h
#ifndef SIMPLEFACTORY_H
#define SIMPLEFACTORY_H
#include <string>
#include <map>
#include <sstream>
template<class TBase, class TIdType = std::string >
class CSimpleFactory
{
public:
typedef TBase* (*CreateCallback)(); // create callback functinos
// register with creator map
bool Register( const TIdType& Id, CreateCallback CreateFcn) {
return m_Creators.insert( std::map< TIdType,
CreateCallback>::value_type( Id, CreateFcn) ).second;
};

// unregister creator
bool Unregister( const TIdType& Id ) {
return m_Creators.erase( Id ) == 1;
};

// here the magic is performed
TBase* Create( const TIdType& Id ) {
// search for creator function
std::map< TIdType, CreateCallback>::const_iterator Iter =
m_Creators.find( Id );
if( Iter != m_Creators.end() ) {
return (Iter->second)();
}
else {
std::string Msg( "Creator function not registered for ==> " );
Msg += ToString( Id );
throw std::runtime_error( Msg );
}
return NULL;
};

private:
std::string ToString( const TIdType& Id ) {
std::istringstream is( Id );
return is.str();
};

private:
std::map< TIdType, CreateCallback> m_Creators;
};

#endif
///////////////// sample code ////////////////////
#include <iostream>

using namespace std;
class CBaseClass {
public:
virtual ~CBaseClass() {};
};

class CSquare : public CBaseClass {

// protect constructor so that the object can be created using
// the factory method only!
CSquare() {}
public:
void draw() { cout << "Square::draw\n"; }
void erase() { cout << "Square::erase\n"; }
virtual ~CSquare() { cout << "Square::~Square\n"; }

// NOTE: this function must be implemented for factory creation!!!
static CBaseClass* Create() { return new CSquare; };
};

int main(int argc, char* argv[])
{
CSimpleFactory<CBaseClass> Factory;
Factory.Register( "CSquare", &CSquare::Create );

// NOTE: If one only uses virtual functions then there is no need
// for this cast!
CSquare* pSquare= static_cast<CSquare*>( Factory.Create( "CSquare2" ) );
pSquare->draw();
delete pSquare;
return 0;
}
There are of course more elegant and sophisticated solutions implementing a
factory but this very simple one is sufficient most of the time.

HTH
Chris
Jul 22 '05 #3

P: n/a
Busin posted:
Classes B, C, D and E are derived from base class A.

A* CreateB();
A* CreateC();
A* CreateD();
A* CreateE();

class X
{
public:
A* ObtainA();
};

int main()
{
Xx;
A* p = x.ObtainA();
}

ObtainA() could return A pointer pointing either to B, or C, or D, or
E.

How to code this so to tell Create() return B, or C, or D, or E at
run-time?


It doesn't. The only difference comes when you try to call a virtual
function of it.

int main()
{
X x;

A* p = x.ObtainA();
p->DoStuff();
}
How does it know whose function to call? It doesn't per se. All it has is a
pointer to that particular function. It just calls the function using the
pointer.

For example:

#include <iostream>

class Car
{
public:
virtual void GetFuel(void) const = 0;
};

class PetrolCar : public Car
{
public:
virtual void GetFuel(void) const
{
std::cout << "Got Petrol!" << std::endl;
}
};

class DieselCar : public Car
{
public:
virtual void GetFuel(void) const
{
std::cout << "Got Diesel!" << std::endl;
}
};
void FuelStation(const Car& car)
{
car.GetFuel();

//It knows which GetFuel function to call simply because
//a Car object contains a hidden pointer to the function!
}

int main()
{
PetrolCar petrol_car;
DieselCar diesel_car;

FuelStation(petrol_car);
FuelStation(diesel_car);
}
-JKop
Jul 22 '05 #4

P: n/a

"JKop" <NU**@NULL.NULL> wrote in message
news:V%*****************@news.indigo.ie...
[SNIP]
How to code this so to tell Create() return B, or C, or D, or E at
run-time?


It doesn't. The only difference comes when you try to call a virtual
function of it.

[SNIP]

And how does this answer the OPīs question on how to create all kinds of
derived objects specified at run-time???

Chris
Jul 22 '05 #5

P: n/a
Chris Theis posted:

"JKop" <NU**@NULL.NULL> wrote in message
news:V%*****************@news.indigo.ie...
[SNIP]
> How to code this so to tell Create() return B, or C, or D, or E at
> run-time?


It doesn't. The only difference comes when you try to call a virtual
function of it.

[SNIP]

And how does this answer the OPīs question on how to create all kinds of
derived objects specified at run-time???

Chris


I must have overestimated their intelligence.

enum DerivedA
{
B,C,D,E
};
A* Create(DerivedA which)
{
A* p_derived_a;

switch (which)
{
case B:
p_derived_a = new B; break;
case C:
p_derived_a = new C; break;
Case D:
p_derived_a = new D; break;
case E:
p_derived_a = new E; break;
default:
throw "Someone-one's stupid";
}

return p_derived_a;
}
-JKop
Jul 22 '05 #6

P: n/a

"JKop" <NU**@NULL.NULL> wrote in message
news:zQ*****************@news.indigo.ie...
Chris Theis posted:

"JKop" <NU**@NULL.NULL> wrote in message
news:V%*****************@news.indigo.ie...
[SNIP]

> How to code this so to tell Create() return B, or C, or D, or E at
> run-time?

It doesn't. The only difference comes when you try to call a virtual
function of it.

[SNIP]

And how does this answer the OPīs question on how to create all kinds of
derived objects specified at run-time???

Chris


I must have overestimated their intelligence.

enum DerivedA
{
B,C,D,E
};
A* Create(DerivedA which)
{
A* p_derived_a;

switch (which)
{
case B:
p_derived_a = new B; break;
case C:
p_derived_a = new C; break;
Case D:
p_derived_a = new D; break;
case E:
p_derived_a = new E; break;
default:
throw "Someone-one's stupid";
}

return p_derived_a;
}
-JKop


And here we are back again at some kind of factory ;-)

Cheers
Chris
Jul 22 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.