473,473 Members | 2,169 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Base class method that returns a pointer to a derived class?

I want to write a base class that includes a member function that creates an
instance of a derrived class and returns a pointer to it.

Problem: The derived class definition has to follow the base class
definition. Therefore I can't specify the return type of the function, that
returns a pointer to the derived class, because the derived class is not yet
known at that point.
Hov can I solve this problem? In a nice manner :)

-- Source Code ------------------------------------------------

class myMainClass
{
public:
mySubClass createSubClassInstance(void);
};
class mySubClass: public myMainClass
{
};

----------------------------------------------------------------------
I'm am looking forward for your clever answer
regards, Teis
Jul 22 '05 #1
3 2325
On Fri, 02 Apr 2004 12:41:56 +0200, Teis Draiby wrote:
I want to write a base class that includes a member function that creates an
instance of a derrived class and returns a pointer to it.
Why? Ideally the base class shouldn't need to know about the derived
class(es)
Problem: The derived class definition has to follow the base class
definition. Therefore I can't specify the return type of the function, that
returns a pointer to the derived class, because the derived class is not yet
known at that point.
Hov can I solve this problem? In a nice manner :)
With a class declaration like this:

class mySubClass;
class myMainClass
{
public:
/* you did say you wanted it to return a pointer */
mySybClass *createSubClassInstance(void)
};
class mySubClass: public myMainClass
{
};

--
NPV

"the large print giveth, and the small print taketh away"
Tom Waits - Step right up

Jul 22 '05 #2
> Why? Ideally the base class shouldn't need to know about the derived
class(es)


Maybe you're right, but here's the reason (don't read it - it is not
important):

It's for a console window in a Win32 application.
The base class creates the console window and has methods like
'putMessage(char *message)'.

Different classes or other logical sections of my program should have the
option to create its own message class instance. These instances output to
the same console window and don't want to initialize any new console
windows. The main reason is to put a prefix to each message indicating who
send the message:

// the message class instance is created as the first thing:
myApp> Welcome to myApp!
// later the fileReader class makes its own instance:
myApp:fileReader> File "myFile.xml" loaded succesfully!

thus I want the base class to create these instances. Since the instances
would do almost the same as the base class except initializing the window
they are implemented as a derived class. It will contain additional methods
like toggleOnOff().

Maybe it's a better idea to make both classes as derrived classes of a new
base class.

regards, Teis


Jul 22 '05 #3
Teis Draiby wrote:
I want to write a base class that includes a member function that creates an
instance of a derrived class and returns a pointer to it.


I posted a very similar problem to the moderated newsgroup and got an
excellent reply. Firstly, it's best to note that the abstract factory
pattern might be more appropriate for what you want (I don't know your
situation). It's something to look into.

This is the trick, originally posted to the moderated group by Maxim
Yegorushkin (altered a little by me):

class Base
{
public:
Base( Derivation ) { ... }

template< class T >
T Create() { return T( Derivation() ); }

// To return a boost::shared_ptr, replace the above with:
// template< class T >
// boost::shared_ptr< T > Create() { return new T( Derivation ); }

protected:
Base() { ... }
struct Derivation {};

private:
// You might want copy ctors and copy assignment operators here.
};

class Derived : public Base
{
public:
Derived( Base::Derivation ) { ... }

protected:
Derived() { ... }
};

Derived can now only be created like this:

Derived d = Base::Create< Derived >();

Any other attempt to create it will cause a compiler error. It works
because the constructor that is used by Create is public, but cannot be
accessed outside the hierarchy because the parameter is a protected
member of Base.

Issues:

1) Two constructors required per class. This is not strictly true, but
if you don't provide a protected default constructor, the public
constructor must pass its parameter back to its base class' constructor.

2) If you leave out the public constructor in a class, but keep the
protected default constructor, you will have a class that cannot be
created (but classes derived from it can still be created). This is
useful when you want this functionality but can't provide a pure virtual
method.

3) Think carefully about what you want to return from Create. As it
stands the object is returned by value (which means the copy-constructor
and copy assignment operator can still be used to construct a new
object). This might be fine for you, but if not you can either make them
private or return a smart pointer instead (such as boost::shared_ptr,
from www.boost.org).

I will say this once more -- you would do well to look into abstract
factory and other design patterns/techniques before using this. Your
choice, though.

Oh, and I don't guarantee that the above code compiles, obviously. :)

-- Pete
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Abhijit Deshpande | last post by:
Is there any elegant way to acheive following: class Base { public: Base() {} virtual ~Base() {} virtual void Method() { cout << "Base::Method called"; return; } };
3
by: Teis Draiby | last post by:
I want to write a base class that includes a member function that creates an instance of a derrived class and returns a pointer to it. Problem: The derived class definition has to follow the base...
7
by: James Brown | last post by:
I have two classes, a base class, and a class base { public: base(); virtual void foo() = 0; }; class derived : public base
10
by: Peter Oliphant | last post by:
Is there a way of defining a method in a base class such that derived classes will call their own version, EVEN if the derived instance is referred to by a pointer to the base class? Note that the...
2
by: reckless2k | last post by:
Client side; knows nothing of Derived: class Base { ... virtual void do_something() } #include "Base.h" void main() {
6
by: Me | last post by:
I need to be able to acces non-virtual members of sublcasses via a base class pointer...and without the need for an explicit type cast. I thought a pure virtual getPtr() that acts as a type cast...
13
by: Rahul | last post by:
Hi Everyone, I was just playing around virtual functions and landed up with the following, class Base1 { public: virtual void sample() { printf("base::sample\n");
2
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual...
10
by: Dom Jackson | last post by:
I have a program which crashes when: 1 - I use static_cast to turn a base type pointer into a pointer to a derived type 2 - I use this new pointer to call a function in an object of the...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
1
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...
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
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...
0
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...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
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...

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.