Return pointer to object of common base

B

Busin

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!
 
B

Bob Hairgrove

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

Chris Theis

[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
 
J

JKop

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
 
C

Chris Theis

[SNIP]
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
 
J

JKop

Chris Theis posted:
[SNIP]
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
 
C

Chris Theis

JKop said:
Chris Theis posted:
[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
 

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

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top