transfer class object from one pointer to another

Z

Zhongqi Pan

I am facing a problem-

I am using

f1(this)

to pass a class object pointer to a function ( say f1)

f1 is defined as follows

f1 (classB *p1)
{

classB *p2 = new class (*p1);

..........

does not transfer the object pointer by the this pointer to p2 - it only
transfers the data values. I need to transfer p1 to p2 because p1 kepts
pointing to old objects and creates problem.

note: classB is the base class of the class whose object is passed to in
f1(this)

Any suggestion ?? Is copy constructor required? ( I have tried it but it
does not work for pointer objects)

If more clarifications are requirted please let me know.

Thank you
 
R

Rolf Magnus

Zhongqi said:
I am facing a problem-

I am using

f1(this)

to pass a class object pointer to a function ( say f1)

f1 is defined as follows

f1 (classB *p1)
{

classB *p2 = new class (*p1);

.........

does not transfer the object pointer by the this pointer to p2 - it
only transfers the data values.

It creates a new dynamically allocated object that is a copy of the
object pointed to by p1 (by copy construction).
I need to transfer p1 to p2 because p1 kepts pointing to old objects
and creates problem.

What do you mean by "transfer p1 to p2"? Do you want p2 to point to the
same object as p1? Then just do:

classB* p2 = p1;

or do you want p2 to point to a new object that is a copy of the one p1
points to?
note: classB is the base class of the class whose object is passed to
in f1(this)

Ah, I think I know now what you mean. You have a pointer to a
polymorphic base class and want to copy an object of a derived class
that is points to. This is not possible with built-in features of C++.
In your example, you get the base class part sliced off and your copy
will only contain that part. In fact, it only is an instance of the
base class.

You need to write a clone member function that does the job. Something
like:

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

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

And then your f1 could look like;

f1(Base* p1)
{
Base* p2 = p1->clone();
//...
}
Any suggestion ?? Is copy constructor required? ( I have tried it but
it does not work for pointer objects)

Your above example _does_ use the copy constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top