more copy constructor when returning value

T

Tony Johansson

Hello!!

Assume you have the following AccountForStudent class

class AccountForStudent
{
public:
AccountForStudent ();
AccountForStudent (long, double);
~AccountForStudent ;
long getNumber() const

private:
Student * stud_;
double balance_;
};

and you have a stand alone function create defined as

AccountForStudent create(long number )
{
AccountForStudent local(number, 0.0);
return local;
}

// and you instansiate an object called global of class AccountForStudent in
this way
AccountForStudent global;

//and you call this stand alone function create in this way
global = create(300);
. . . .

Now to my question I just want to check with you that I have understood it
right.

When this function create is called a local object named local is created in
the function.
When the function create is doing return local the copy constructor is
called and
a temporary object is created lets call it temp. Now the object temp and
local is sharing the Student object.

We can imagine the code behind is something like
AccountForStudent temp(local);
this mean an object temp is created and initialized using object local.
This object temp is assigned to object global using the assignment operator.
After this statement global = create(300);
the temp object destructor is called and here we do delete Student leaving
the global object without any Student object.

Give me some feedback on this please.
Correct me if I'm wrong in some place.


//Tony
 
K

Karl Heinz Buchegger

Tony said:
Give me some feedback on this please.
Correct me if I'm wrong in some place.

Listen.
It doesn't matter when or where that copy constructor is used.
At the moment it is used you have that problem, be it when
passing an object by value or returning an object per value.

At the moment the copy constructor makes what we call a 'shallow copy'
(a memberwise copy) you run into troubles with that type of setup.

It is the fact that the copy constructor does the wrong thing, that
creates that problem. When or where the copy constructor is used
is unimportant.
 

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

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,250
Latest member
Charlesreero

Latest Threads

Top