473,382 Members | 1,359 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,382 software developers and data experts.

Copying an object using base class pointers

Hi!
I have a class with a private member which is a pointer to an abstract
class, which looks something like this:

class Agent
{
public:
void Step( Base* newB );

private:
Base* previousB;
};

For each time Step() is called, it should copy the contents of newB to
previousB, as the next time Step() is called, it needs to do stuff with
previousB. Now, how can I do that without knowing what derived class
newB actually is? Just copying the pointer won't work, since what it
points to may well change between calls. Can I use memcpy in some way,
or do I need to make a derived class of Agent which uses a "Derived
previousD;" instead of "Base* previousB;"?

/ martin

Jul 19 '05 #1
5 6129
Martin Magnusson escribió:
For each time Step() is called, it should copy the contents of newB to
previousB, as the next time Step() is called, it needs to do stuff with
previousB. Now, how can I do that without knowing what derived class
newB actually is? Just copying the pointer won't work, since what it
points to may well change between calls. Can I use memcpy in some way,


Define a virtual function called clone or similar that returns a newed
copy of the object and implement it on all derived classes. This type of
functions are sometimes called "virtual constructors".

Regards.
Jul 19 '05 #2

"Martin Magnusson" <lo*******@frustratedhousewives.zzn.com> wrote in message news:bk**********@green.tninet.se...
. Can I use memcpy in some way,
or do I need to make a derived class of Agent which uses a "Derived
previousD;" instead of "Base* previousB;"?


If I understand what you want, you need a concept sometimes
referred to as a virtual constructor. I call it a "clone" function.
It involves a change to your objects.

class Base {
public:
virtual Base* clone() = 0;
//...
};

class DerivedA : public Base {
public:
Base* clone() { return new DerivedA(this); }
//...
};

class Agent {
public:
void Step(Base* newB) {
previousB = newB->clone();
};
private:
Base* previousB;
};
Jul 19 '05 #3
Hi Martin,
"Martin Magnusson" <lo*******@frustratedhousewives.zzn.com>
I have a class with a private member which is a pointer to an abstract
class, which looks something like this:

class Agent
{
public:
void Step( Base* newB );

private:
Base* previousB;
};

For each time Step() is called, it should copy the contents of newB to
previousB, as the next time Step() is called, it needs to do stuff with
previousB. Now, how can I do that without knowing what derived class
newB actually is?


You can't. At least not without limitations.

I propose a solution:

Have the base class define a virtual function whose intention is to copy a
source object into itself. Maybee like this:

void Assign(const Base* aSource);

Either impliment the functions in the base class, or make the base class
pure virtual. Then in subclasses polymorphically override the function to
perform the assignment of aSource to *this. Each implimenation will
(naturally) be different and may call inherited versions of the function to
help complete the job.

Have all subclasses define copy constrcutors (you should always define copy
constrcutors anyways):

Base(const Base* aSource);
Base(Base* aSource);

But the polymorphic Assign cannot be used alone to solve the problem as you
can probably already see... The trouble comes in if aSource isnt the exact
same type (but inherits from) the implimenting type. The implimenting type
may not (should not) be aware of the various inheriting sub-types. Even if
it was, it would be unable to destroy itself and recreate itself as the
correct subtype.

Delegate this job to the aggregating object (Agent). Thus - your Step()
function would first do a type check on the newB parameter and if it is the
same type as the previousB, simply call previousB->Assign(newB);

However - if the types are not exactly the same, then immediately destroy
the previousB, create a new instance of the exact same type of newB (and
pass newB to its copy constructors) then simply assign the new object to
previousB.

If you want to get really fancy here - you may wish to consider using a the
design pattern of a factory class to create objects in the scope of Step() -
thus removing the need of the Agent class to explicitly know the subtype of
newB and previousB and execute different conditional code based on the type
(which is almost always a no-no). This pattern is especially good in this
scenario if there are a large number of subtypes or you expect to add
numerous subtypes in the future. I wont go into the details of how to
impliment the factory pattern here - have a look at a design patterns book
for more info.

Thats how I would do it.

But maybee there is a better way? Anybody have a better way?

Zack.
Jul 19 '05 #4
Ron Natalie wrote:
If I understand what you want, you need a concept sometimes
referred to as a virtual constructor. I call it a "clone" function.


Thanks, both of you! That's exactly it!

/ martin

Jul 19 '05 #5

"Ron Natalie" <ro*@sensor.com> wrote in message news:3f***********************@news.newshosting.co m...
Base* clone() { return new DerivedA(this); }


Gak...
new DerivedA(*this);
Jul 19 '05 #6

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

Similar topics

4
by: Dave Theese | last post by:
Hello all, The example below demonstrates proper conformance to the C++ standard. However, I'm having a hard time getting my brain around which language rules make this proper... The error...
13
by: Walt Karas | last post by:
The following gives an error in the declaration of the member function x() of the class template Tpl, compiliing with a recent version of GCC under Solaris: class A { }; class B { }; ...
2
by: Andrew Ducker | last post by:
My UserControl base class has an event handling method in it. I want to use this for several controls on a subclass of this base class. Normally, I can just click on the drop-down and the methods...
0
by: Dave | last post by:
Hi, I'm having a problem with my web page. I made a user aspx page Child.aspx that inherits from a base class TemplatePage (TemplatePage.cs). The template class overrides Render, streams some...
4
by: FacultasNetDeveloper | last post by:
I am extending FileSystemInfo class so that I can Implement Icomparable. My custom class looks like: Class FSFileSystemInfo Inherits FileSystemInfo : Implements Icomparable Function...
4
by: Jeff | last post by:
The derived class below passes a reference to an object in its own class to its base calss constructor. The code compiles and will run successfully as long as the base class constructor does not...
2
by: kaferro | last post by:
I have a base class that has about ten variables. Later, I have a derived class that adds five more variables. In the derived class' setData() function, I pass an instance of the base class, and...
1
by: manontheedge | last post by:
can someone clarify what base class pointers are for me. I know what Inheritence is and how abstract base classes work with derived classes, but i'm a little lost on base class pointers. I don't...
12
by: bgold | last post by:
Hey. I have a base class (SPRITE), and using this base class I have derived a large number of derived classes (PERSON, BULLET, MISSILE, etc.). Now, at a certain point in my program, I have a pair...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.