473,545 Members | 2,073 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2287
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**********@Ho me.com
Jul 22 '05 #2

"Busin" <bu****@fidrep. com> wrote in message
news:iZ******** ************@bg tnsc04-news.ops.worldn et.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* (*CreateCallbac k)(); // create callback functinos
// register with creator map
bool Register( const TIdType& Id, CreateCallback CreateFcn) {
return m_Creators.inse rt( std::map< TIdType,
CreateCallback> ::value_type( Id, CreateFcn) ).second;
};

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

// here the magic is performed
TBase* Create( const TIdType& Id ) {
// search for creator function
std::map< TIdType, CreateCallback> ::const_iterato r 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_er ror( Msg );
}
return NULL;
};

private:
std::string ToString( const TIdType& Id ) {
std::istringstr eam 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::~Squar e\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.Registe r( "CSquare", &CSquare::Creat e );

// NOTE: If one only uses virtual functions then there is no need
// for this cast!
CSquare* pSquare= static_cast<CSq uare*>( 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(con st 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(pet rol_car);
FuelStation(die sel_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
13787
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 would be more orthogonal if a method could only have one return statement. --
9
4975
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 pointer which points to an instance of a derived class, but when I pass that base class pointer into a function, it can't access the derived...
37
4952
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 signature. When developing this lib, I figured that the pointer-to-member-function, although seemingly an attractive solution, does not work well...
10
40636
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 referencelike: void func(int & x)
4
157982
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
5147
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 description would be as clear as an example. ----------- class ParentA {};
14
1458
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, Visual Studio 2005 Code:
5
3622
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 10 member functions. Can switch be replaced to member function pointer array? Please provide me an example of source code to show smart pointer...
18
2437
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 that one can implement a very basic form of subclassing in C (the gurus certainly already know this, but it was news to me). What i've done (shown...
0
7470
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7659
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7428
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7760
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5334
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4949
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3455
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
709
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.