|
-
December 29th, 2008, 11:12 PM
#7
Re: Functions returning my user-defined class (w/pointer) don't like operator=.
 Originally Posted by oliveman
Here is a class which produces the errors.
In addition to what CPUWizard points out, your code has other runtime errors. Also, you need to format your code a little better, since too much of it is not indented properly and is hard to read.
First, usage of std::vector eliminates the need for copy constructor and assignment operator. However, here is your mistake:
Code:
myClass::myClass(const myClass & original)
{
int k=0;
while (k<5)
{
ptr[k]=original.Read(k); // Error! Invalid memory access
k++;
}
}
See the line in red? It is wrong, since ptr was not allocated.
The fix to both the default and copy constructor is to make sure that ptr is allocated on initialization of the object. You would use the initializer list instead of allocating it within the constructor body.
Code:
myClass::myClass() : ptr(new int[5])
{ }
myClass::myClass(const myClass & original) : ptr(new int[5])
{
k = 0;
while (k<5)
{
ptr[k]=original.Read(k);
k++;
}
}
Regards,
Paul McKenzie
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|