473,396 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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!
Jul 22 '05 #1
6 2280
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

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

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

"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

94
by: John Bailo | last post by:
The c# *return* statement has been bothering me the past few months. I don't like the fact that you can have different code paths in a method and have multiple return statements. To me, it...
9
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class...
37
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined...
10
by: Robert | last post by:
Hello all, I am a C programmer learning C++. And I am confused with function Pass by Pointer * or Pass by Reference &. Function pass by pointer like: void func(int * x) And function pass by...
4
by: Isaac | last post by:
Hi mates I want to know a simple program of return array from function ? Do I need to use pointer to return the address of the first element in an array. Isaac
13
by: ctor | last post by:
Hi, I'm experiencing an annoying issue. Here is a simplified idea of what I am trying to do. Inclusion guards aren't shown for readability. I hope this isn't too confusing; I don't think a...
14
by: cweisbrod | last post by:
All, I'm seeing something very strange and was hoping someone might have some insight into the cause of what I'm seeing. I have the following scenario: Platform: Microsoft Windows XP Pro,...
5
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call...
18
by: Stephan Beal | last post by:
Hi, all! Before i ask my question, i want to clarify that my question is not about the code i will show, but about what the C Standard says should happen. A week or so ago it occurred to me...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.