473,386 Members | 2,129 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,386 software developers and data experts.

Polymorphic assignment?

I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all. All the derived classes have a unique factory method which
returns a new object of the derived type.

The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}

The rationale is that:

(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method

(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.

This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.

Is this code fixable? Is there any way to do this without writing 150
clone routines?

Thanks -

Ed
Aug 10 '05 #1
7 3890

Mr. Ed wrote:
I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all. All the derived classes have a unique factory method which
returns a new object of the derived type.

The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}
slice. obj is a BaseClass object, it will /always/ be a BaseClass
object; it will /never/ be a derived class object. This initialization
slices off the derived object's behavior when the /copy/ into the obj
is made. Same goes for your return value of clone and factory. You need
to be working with pointers (or references, but they don't apply here)
if you expect polymorphic behavior.

The rationale is that:

(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method

(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.

This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.

Is this code fixable? Is there any way to do this without writing 150
clone routines?

Thanks -

Ed


Aug 10 '05 #2
Mr. Ed wrote:
I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all.
Why do you have them, then?
All the derived classes have a unique factory method which
returns a new object of the derived type.
What's its signature? Is it a static member function? If not, what
object do you use to call your factory?
The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
What does 'factory' return, an object? If so, how would you avoid
slicing?
obj = *this; // line 2
At this point 'obj' contains _no_ traces of the derived object 'factory'
may have returned.
return obj;
}

The rationale is that:

(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method
But it immediately loses all traces of how it was created when you
initialise the BaseClass object with it.
(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.
In what given derived class? 'obj' has the type BaseClass.
This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.
No, it doesn't. You need 'obj' to be either a reference or a pointer
to invoke anything polymorphically. It can't be a reference because what
would it be a reference of? It could be a pointer to a dynamic object.
Is this code fixable? Is there any way to do this without writing 150
clone routines?


I don't know how your 'factory' method works, but it is most fitting to
have it accept a "prototype":

BaseClass* factory(BaseClass* proto = 0)
{
if (proto)
return new Baseclass(*proto); // copy-construction
else
return new BaseClass(); // default-construction
}

This way you may need to create a parameterized constructor for each
derived class to accept a reference to base. Whatever it does with it
is only its own business.

Another solution if your 'function' member actually returns a pointer
to a new'ed object. Then polymorphic assignment is possible:

virtual BaseClass& operator=(BaseClass const other&); // implement
// as you see fit in derived
BaseClass* clone() {
BaseClass* pobj = this->factory();
*pobj = *this; // this will invoke the virtual operator
return pobj;
}

You will have to still implement operator=(BaseClass const&); in every
derived class (similar to the parameterized constructor I wrote about
earlier).

V
Aug 10 '05 #3
Sorry guys -
BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}
I over-simplified my code too much; the factory method returns a smart
pointer to the derived object, and 'obj' is of a smart pointer type. A
better summary would have been:

SP_BaseClass BaseClass::clone() {
SP_BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}

So, there's no slicing problem in line 1.

On Wed, 10 Aug 2005 13:57:55 -0400, Victor Bazarov
<v.********@comAcast.net> wrote:
Mr. Ed wrote:
I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all.


Why do you have them, then?


Long story, but basically to have a heterogeneous tree of these
classes rather than a homogeneous tree.
All the derived classes have a unique factory method which
returns a new object of the derived type.


What's its signature? Is it a static member function? If not, what
object do you use to call your factory?


static member function in each derived class:

class derived_x {
...
static RefType factory(void) { return RefType(new(derived_x)); }
};

where 'RefType' is a reference-counted smart ptr type.

I'm just working through the rest of your comments. At first sight, it
seems that either I have to use your suggestion of a custom assignment
operator in each derived class, or a custom clone method in each
derived class, which means that I have to add a lot of lines of text
which are basically redundant... :(

Cheers

Ed
Aug 10 '05 #4
Mr. Ed wrote:
[...]
All the derived classes have a unique factory method which
returns a new object of the derived type.
What's its signature? Is it a static member function? If not, what
object do you use to call your factory?

static member function in each derived class:

class derived_x {


class derived_x : public base {
...
static RefType factory(void) { return RefType(new(derived_x)); }
};
And how the hell can you call the right one (supposedly one in a derived
class) from a base class member function 'clone'? There is no way. You
need a polymorphic factory.
where 'RefType' is a reference-counted smart ptr type.

I'm just working through the rest of your comments. At first sight, it
seems that either I have to use your suggestion of a custom assignment
operator in each derived class, or a custom clone method in each
derived class, which means that I have to add a lot of lines of text
which are basically redundant... :(


Nobody said life was easy... Not it this thread, anyway.

V
Aug 10 '05 #5
On Wed, 10 Aug 2005 14:34:21 -0400, Victor Bazarov
<v.********@comAcast.net> wrote:
Mr. Ed wrote:
[...]
All the derived classes have a unique factory method which
returns a new object of the derived type.

What's its signature? Is it a static member function? If not, what
object do you use to call your factory?

static member function in each derived class:

class derived_x {


class derived_x : public base {
...
static RefType factory(void) { return RefType(new(derived_x)); }
};


And how the hell can you call the right one (supposedly one in a derived
class) from a base class member function 'clone'? There is no way. You
need a polymorphic factory.


It is polymorphic. The base class has a virtual factory method; the
derived classes over-ride it with a static member. I'm assuming that
in line 1:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
...
}

the correct derived class is called. Are you saying that this is
wrong?

Cheers

Ed
Aug 10 '05 #6
Mr. Ed wrote:
On Wed, 10 Aug 2005 14:34:21 -0400, Victor Bazarov
<v.********@comAcast.net> wrote:

Mr. Ed wrote:
[...]

>All the derived classes have a unique factory method which
>returns a new object of the derived type.

What's its signature? Is it a static member function? If not, what
object do you use to call your factory?
static member function in each derived class:

class derived_x {
class derived_x : public base {

...
static RefType factory(void) { return RefType(new(derived_x)); }
};


And how the hell can you call the right one (supposedly one in a derived
class) from a base class member function 'clone'? There is no way. You
need a polymorphic factory.

It is polymorphic. The base class has a virtual factory method; the
derived classes over-ride it with a static member.


WHAT???
I'm assuming that
in line 1:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
...
}

the correct derived class is called. Are you saying that this is
wrong?


Uh... Wrong? How should I break it to you?... You simply cannot
override a virtual member function with a static one. Otherwise, no,
it's not wrong.

V
Aug 10 '05 #7

Mr. Ed wrote:
I have a base class which has about 150 derived classes. Most of the
derived classes are very similar, and many don't change the base class
at all. All the derived classes have a unique factory method which
returns a new object of the derived type.

The problem I've got is that I now need to polymorphically clone a
derived class object, but I don't want to write a separate 'clone'
method for each of these 150 classes. Instead, I thought I might get
away with just writing one base class clone routine instead, something
like this pseudo-code:

BaseClass BaseClass::clone() {
BaseClass obj = this->factory(); // line 1
obj = *this; // line 2
return obj;
}

The rationale is that:

(line 1) 'obj' is correctly created as a derived-class object, because
'this->factory()' calls the polymorphic derived-class factory method

(line 2) 'obj = *this' uses the default copy assignment operator in a
given derived class to copy all the derived-class members to 'obj'.

This doesn't work, however, because the compiler doesn't know which
operator= to use in line 2. Basically, line 2 is asking for a
polymorphic assignment.

Is this code fixable? Is there any way to do this without writing 150
clone routines?


I recommend using the following clone smart pointer class:
http://code.axter.com/clone_ptr.h

The above clone smart pointer, does not need a clone method. It can
correctly duplicate the correct derived copy of itself through the
assignment operator.
Example code:
void CopyCorrectDerivedTypeDemo()
{
std::vector<clone_ptr<BaseClass> > vBaseClass;
//Setup data using base and derived type classes
vBaseClass.push_back(new BaseClass( "3" ));
vBaseClass.push_back(new Derived_B( "2" ));
vBaseClass.push_back(new BaseClass( "1" ));
vBaseClass.push_back(new Derived_A( "5" ));
vBaseClass.push_back(new BaseClass( "4" ));

//Copy contents from one container to another
std::vector<clone_ptr<BaseClass> > vBaseClass_Copy(vBaseClass.begin(),
vBaseClass.end());

//Display results
for (int i = 0;i < vBaseClass_Copy.size();++i)
{
vBaseClass_Copy[i]->WhoAmI();
}
In above example code, the vBaseClass_Copy container gets the correct
dervied copy from the vBaseClass container.
This smart pointer does not share the pointer, and instead has strict
pointer ownership.

Aug 11 '05 #8

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

Similar topics

9
by: Dave | last post by:
What is the expected output of this program and why??? #include <iostream> using namespace std; class base {
20
by: verec | last post by:
One problem I've come accross in designing a specific version of auto_ptr is that I have to disntiguish between "polymorphic" arguments and "plain" ones, because the template has to, internally,...
1
by: verec | last post by:
Last week I asked here how I could detect that a T was polymorphic, and received very thoughtful and useful replies that I used straight away. Thanks to all who answered. This week, it turns...
7
by: James Fortune | last post by:
In response to different users or situations (data context) I transform the appearance and characteristics of Access Forms through code. This seems to fit in with the idea of polymorphism. Do...
10
by: Christian Christmann | last post by:
Hi, how do I define an assignment operator which is supposed to copy all member attributes of one object to another where both objects are given as pointers? Example: CLASS_A *source = new...
11
by: anongroupaccount | last post by:
What measures should be taken to avoid this sort of thing? class Base { }; class Derived1 : public Base { private: int i, j, k;
6
by: toton | last post by:
Hi, I am inheriting a vector<Pointclass as a PointVector non-polymorphically, to add several additional functionalities to it. I know the dangers of inheriting a container class, as it doesn't...
12
by: siddhu | last post by:
Dear experts, #include <stdio.h> class Base { }; class Der1:public Base {
2
by: Daniel Pitts | last post by:
I'm trying decide on the best way to structure the memory management in my program. I have a class (lets call it World), which contains a collection of Entity objects. Entity in turn,...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...

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.