473,761 Members | 8,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6162
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*******@frus tratedhousewive s.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*******@frus tratedhousewive s.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.newshosti ng.com...
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
12822
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 below *should* happen, but my question to the community is *why* does it happen? Any answer will be appreciated, but a section and paragraph number from the C++ Standard would be especially appreciated.
13
2825
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 { }; template <typename Base> class Tpl : protected Base {
2
1447
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 that fit the correct signature appear - however ones from the base class don't! If I go in and change the generated code myself, it works - so things are set up correctly - it just doesn't appear in the dropdown. Anyone else encountered this?
0
1059
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 html from a header template html file, calls base.Render(), and then streams some html from a footer template file. I put some text in the body of child.aspx and it looks perfect. Now I want to put a user control on child.aspx that draws a little...
4
1593
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 CompareTo(ByVal o As Object) As Integer _ Implements IComparable.CompareTo My issue comes when I try to set an instance of FSFileSystemInfo to an object that is FileSystemInfo type. Such as:
4
5247
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 attempt to access the object -- since m_object is not actually created and initizialized until after the base constructor has been called. Any thoughts on the practice below? class Base { public:
2
2077
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 use it to set the derived class' base class variables. Is there a problem with this structure? //cComponent is the base class void setData(cComponent tmpComponent, float tmpPosition, char roll_or_new, int orderNum)
1
2210
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 know why i'm not getting it. what i'm trying to do is have one class contain base class pointers to each derived class ( of another base class ) ... and at this point i'm just confused and i'm not sure how to go about it. I looked around on the...
12
2870
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 of pointers, where each is a pointer to the base class (each is a SPRITE *). I know that each of these pointers actually points to one of the derived classes, even though the type of the pointer is SPRITE *, but I don't know which derived class it...
0
10136
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9923
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8813
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5266
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
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 we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.