 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Busin Guest
|
Posted: Tue Jun 29, 2004 7:35 am Post subject: Return pointer to object of common base |
|
|
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!
|
|
| Back to top |
|
 |
Bob Hairgrove Guest
|
Posted: Tue Jun 29, 2004 7:52 am Post subject: Re: Return pointer to object of common base |
|
|
On Tue, 29 Jun 2004 07:35:42 GMT, "Busin" <businm (AT) fidrep (DOT) com> wrote:
| Quote: | 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
[email]NoSpamPlease (AT) Home (DOT) com[/email]
|
|
| Back to top |
|
 |
Chris Theis Guest
|
Posted: Tue Jun 29, 2004 8:47 am Post subject: Re: Return pointer to object of common base |
|
|
"Busin" <businm (AT) fidrep (DOT) com> wrote
[SNIP]
| Quote: | 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::drawn"; }
void erase() { cout << "Square::erasen"; }
virtual ~CSquare() { cout << "Square::~Squaren"; }
// NOTE: this function must be implemented for factory creation!!!
static CBaseClass* Create() { return new CSquare; };
};
int main(int argc, char* argv[])
{
CSimpleFactory
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
|
|
| Back to top |
|
 |
JKop Guest
|
Posted: Tue Jun 29, 2004 9:55 am Post subject: Re: Return pointer to object of common base |
|
|
Busin posted:
| Quote: | 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
|
|
| Back to top |
|
 |
Chris Theis Guest
|
Posted: Tue Jun 29, 2004 3:10 pm Post subject: Re: Return pointer to object of common base |
|
|
"JKop" <NULL (AT) NULL (DOT) NULL> wrote
[SNIP]
| Quote: |
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
|
|
| Back to top |
|
 |
JKop Guest
|
Posted: Tue Jun 29, 2004 4:32 pm Post subject: Re: Return pointer to object of common base |
|
|
Chris Theis posted:
| Quote: |
"JKop" <NULL (AT) NULL (DOT) NULL> wrote in message
news:V%aEc.3434$Z14.4419 (AT) news (DOT) 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
|
|
| Back to top |
|
 |
Chris Theis Guest
|
Posted: Tue Jun 29, 2004 5:03 pm Post subject: Re: Return pointer to object of common base |
|
|
"JKop" <NULL (AT) NULL (DOT) NULL> wrote
| Quote: | Chris Theis posted:
"JKop" <NULL (AT) NULL (DOT) NULL> wrote in message
news:V%aEc.3434$Z14.4419 (AT) news (DOT) 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
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|