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

Class Templates, Pointers, and transferring data between class objects

36
I've been learning C++ for about 6 weeks now, and I've been able to figure out pretty much everything I have had a problem with.

This time, I'm at a loss. I'm not learning from the greatest book anyway, but here's the deal:

I was learning about template classes, and how to transfer data between two objects of the same class with pointers involved.

I was shown how to make the code "safe" by adding a copy constructor, an overloaded assignment operator, and a destructor.

The code only had one object, and I tried to add another object so I could transfer that data, and boom. Problem.

The code compiles with no errors, however when you run it, it gets to the last 'for' loop and crashes.

Here's the code:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5.     template <class T>        
  6.     class Array    
  7.     {                
  8.         T *ptr_to_array;
  9.         int number;
  10.     public:
  11.         Array( int number_of_elements );
  12.         Array( const Array &a );
  13.         ~Array();
  14.         T& operator=( const Array &a );
  15.         T& operator[]( int index ){ return ptr_to_array[index]; }
  16.     };
  17.  
  18.  
  19.         template <class T>
  20.         Array<T>::Array( int number_of_elements )
  21.         {
  22.             number = number_of_elements;
  23.             ptr_to_array = new T[number];
  24.         }    
  25.  
  26.  
  27.         template <class T>
  28.         Array<T>::Array( const Array &a )
  29.         {
  30.             number = a.number;
  31.             T *ptr_to_array = new T[number];
  32.  
  33.             for( int index = 0; index < number; index++ )
  34.             {
  35.                 ptr_to_array[index] = a.ptr_to_array[index];
  36.             }
  37.         }
  38.  
  39.  
  40.         template <class T>
  41.         T& Array<T>::operator=( const Array &a )
  42.         {
  43.             if ( this == &a ) return *this;
  44.             delete[] ptr_to_array;        
  45.  
  46.             number = a.number;
  47.             T *ptr_to_array = new T[number];
  48.  
  49.             for( int loop = 0; loop < number; loop++ )
  50.             {
  51.                 ptr_to_array[loop] = a.ptr_to_array[loop];
  52.             }
  53.  
  54.             return *this;
  55.         }
  56.  
  57.  
  58.         template <class T>
  59.         Array<T>::~Array()
  60.         {
  61.             cout << "Deleting allocated memory" << endl;
  62.             delete[] ptr_to_array;
  63.         }
  64.  
  65.  
  66.  
  67. int main()
  68. {
  69.  
  70.     const int nmbr_kids[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  71.     Array<float> scores( 10 );
  72.  
  73.     for( int loop = 0; loop < 10; loop++ )
  74.     {
  75.         scores[loop] = nmbr_kids[loop];
  76.     }
  77.  
  78.  
  79.     for( int loop = 0; loop < 10; loop++ )
  80.     {
  81.         cout << "This is the value in scores element" << loop << ": " << scores[loop]  << endl;
  82.     }
  83.     cout << "\n\n";
  84.  
  85.  
  86. // Problem code lies below...
  87.  
  88.     Array<float> newScores( scores );
  89.  
  90.     for( int loop = 0; loop < 10; loop++ )
  91.     {
  92.         cout << "This is the value in newScores element" << loop << ": " << newScores[loop] << endl;
  93.     }
  94.  
  95.  
  96.  
  97.     return 0;
  98. }
  99.  
As you can see, it's long.

I added the array to the constant integer in main. (originally, it initialized to 5)
I also added the 'for' loops in main. (the ones in the method definitions are from the book )

This isn't homework or anything.
I just want to learn, so it's no rush. 8^)

-Soneji
Apr 13 '07 #1
9 2047
Soneji
36
Nevermind.

I found some help.

Why the book was telling me to create new pointers in the copy constructor, and
assignment operator overload method, is beyond me.

If you need the answer, it's easy:

T *pnt_to_array = new T[number];

should read:

pntr_to_array = new T[number];
Apr 14 '07 #2
JosAH
11,448 Expert 8TB
Why the book was telling me to create new pointers in the copy constructor, and
assignment operator overload method, is beyond me.
By default, i.e. if you don't specify otherwise, when a object is copied the
values of all the members are copied from one object to its copy. Suppose
one of those members is a pointer pointing to somewhere. After copying all
member values both objects have a member pointing to the same thing.

This is scary because if the destructor desctructs that thing when the object
itself is destructed, the *other* object points to a zombie thing which has
been reaped and belongs to the memory heap again.

The default copy is called a 'shallow' copy and you most of the time are
supposed to make a 'deep' copy of objects (unless you have very special
reasons not to do so).

kind regards,

Jos
Apr 14 '07 #3
Soneji
36
Oops!

Sorry, that seemed clearer when I wrote it...

I know why I need to allocate new memory for the second object's pointer.

What I meant was, the author had me do this:

T *pntr = new T[number]; // creating a new pointer, and allocating memory.

instead of:

pntr = new T[number]; // allocating new memory for the object's already
// existing pointer.

The class itself holds the pointer. There was no need to make a new one, just
allocate new memory for the existing one in the copy constructor.

Isn't that correct?

I appreciate the help, There have been a few rough patches here and there.

Thanks!

-Soneji
Apr 14 '07 #4
JosAH
11,448 Expert 8TB
Isn't that correct?
Yep, that's correct; of course it doesn't make sense to allocate memory and
assign it to a local variable when you're deep copying an object. The local
variable will be gone when the function returns and the memory will be lost
for the posterity (read: memory leak).

kind regards,

Jos
Apr 14 '07 #5
Soneji
36
Yep, that's correct; of course it doesn't make sense to allocate memory and
assign it to a local variable when you're deep copying an object. The local
variable will be gone when the function returns and the memory will be lost
for the posterity (read: memory leak).

kind regards,

Jos

I want to make sure of this...

I understand what you're saying about the local variable.
The variable will lose scope once you leave the method, so allocating memory
for it is... Not smart.

But in this situation, (shortened from above):
Expand|Select|Wrap|Line Numbers
  1.     template <class T>
  2.     Array<T> Array<T>::operator=(const Array &a)
  3.     {
  4.         if (this == &a)  return *this;
  5.         delete[] ptr_to_array                  // *** Question 2 ***
  6.         number = a.number;
  7.         ptr_to_array = new T[number];   // *** Question 1. ***
  8.     };
  9.  
In question 1: 'ptr_to_array' is a pointer declared in the class, and it's the reason
for the "deep copy", so would this be the correct way to do it?

Or is it bad practice to allocate the memory for it, inside the method this way,
and if so... how should it be done?

As for question 2: Is the delete here to remove object1's pointer value from
object2's pointer?

When you allocate new memory for a pointer that holds a value, does it preserve
the value already within, or is it thrown off into limbo?

I really appreciate the help. I thought I had a good grasp on class pointers, and
allocating memory... I guess I was wrong.

8^)
Thanks again!

-Soneji
Apr 15 '07 #6
JosAH
11,448 Expert 8TB
Expand|Select|Wrap|Line Numbers
  1.     template <class T>
  2.     Array<T> Array<T>::operator=(const Array &a)
  3.     {
  4.         if (this == &a)  return *this;
  5.         delete[] ptr_to_array                  // *** Question 2 ***
  6.         number = a.number;
  7.         ptr_to_array = new T[number];   // *** Question 1. ***
  8.     };
  9.  
In question 1: 'ptr_to_array' is a pointer declared in the class, and it's the reason
for the "deep copy", so would this be the correct way to do it?
Yep, that's the way to do it; the object's member pointer should point to some
memory which you've just allocated.

As for question 2: Is the delete here to remove object1's pointer value from
object2's pointer?
Your new object's pointer member doesn't point to anything yet. You are
supplying a copy constructor so C++ leaves it all up to you to populate your
new object. If you hadn't supplied a copy constructor C++ would've generated
one which copies all members one by one (a shallow copy). Since you're
supplying your own copy ctor, you have to take care that all members are
initialized properly. And because that pointer didn't point to anything yet there's
no reason to delete anything.

When you allocate new memory for a pointer that holds a value, does it preserve
the value already within, or is it thrown off into limbo?
Preserve what? Most likely that content of the freshly allocated memory contains
rubbish or all zeros or whatever the default constuctor of type T had put into
every slot of that array. You want the array to contain exactly what the other
object (the one you're copying from) had in that array, so you have to copy that.

kind regards,

Jos
Apr 15 '07 #7
Soneji
36
Yep, that's the way to do it; the object's member pointer should point to some
memory which you've just allocated.


Your new object's pointer member doesn't point to anything yet. You are
supplying a copy constructor so C++ leaves it all up to you to populate your
new object. If you hadn't supplied a copy constructor C++ would've generated
one which copies all members one by one (a shallow copy). Since you're
supplying your own copy ctor, you have to take care that all members are
initialized properly. And because that pointer didn't point to anything yet there's
no reason to delete anything.
Ahh... See what I meant about not learning from the best book. :)

I couldn't figure out why that 'delete' was there, now I know, I don't need it!

Thanks so much for that!


Preserve what? Most likely that content of the freshly allocated memory contains
rubbish or all zeros or whatever the default constuctor of type T had put into
every slot of that array. You want the array to contain exactly what the other
object (the one you're copying from) had in that array, so you have to copy that.

kind regards,

Jos
You answered both my questions. :)

On the preserving value thing, I went dumb for a second. If the default copy
constructor was used, every value that was in object 1 would be transferred
into object 2. (leading to problems with the pointer)

My question meant, when they are transferred, and I make new memory,
would object 1's pointer still be in the memory, or would the memory overwrite
it?
But...

After reading your answer, I realized my mistake. Object 1's values would not
be transferred until I put the code in for it to do so.

I had a brain fart, and thought that object 1's values would be transferred before
my CC ran... but the default CC won't run with mine there.

Right? I hope this finally clears up my confusion.

Thanks you so much for your help.
You have been very patient with me and you didn't respond with a
holier-than-thou attitude like some people do.
Maybe one day, I can repay the favor. :)

Thanks again!
-Soneji
Apr 15 '07 #8
JosAH
11,448 Expert 8TB
Ahh... See what I meant about not learning from the best book. :)

I had a brain fart, and thought that object 1's values would be transferred before
my CC ran... but the default CC won't run with mine there.

Right? I hope this finally clears up my confusion.
Yep, right. And about a lot of those books: those trees used for those books
would've been worth more when turned into crappy toilet paper. Don't buy any
of those "... in twenty-one days", nor "... for dummies", nor anything at all
that has "Herbert Schieldt" on the cover. It's a waste of money.

kind regards,

Jos ;-)
Apr 15 '07 #9
Soneji
36
Yep, right. And about a lot of those books: those trees used for those books
would've been worth more when turned into crappy toilet paper. Don't buy any
of those "... in twenty-one days", nor "... for dummies", nor anything at all
that has "Herbert Schieldt" on the cover. It's a waste of money.

kind regards,

Jos ;-)

Thanks for the heads up! Unfortunately I bought the C++ in 21 days 4Th Ed.
5 years ago. :(

But it's gotta be better than the C++ Black Book that I'm learning from!

Almost done with it though ( thank god! )

Thanks again for all your help, it's really been... helpful! (oh, that was bad.)

Seriously, Thanks!

-Soneji
Apr 16 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: David Goodyear | last post by:
At the moment im experimenting with ideas in C++ and would really like to solve the following, please please help. Sorry i dont even know what the subject is this would come under? :( Sorry if...
9
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I...
9
by: Jon Wilson | last post by:
I have a class which needs to accumulate data. The way we get this data is by calling a member function which returns float on a number of different objects of different type (they are all the...
12
by: Rennie deGraaf | last post by:
I have a system that looks like this: class AbstractBase { /* ... */ }; template <class T> class Impl : public AbstractBase { /* ... */ }; // ... Impl<int> i; Impl<float> f;...
7
by: Fabien | last post by:
Hi! I'm trying to do something that is perhaps impossible to do. I have two classes : Attribute and SetOfAttributes Here is Attribute.h template <typename T> class Attribute
7
by: mathieu | last post by:
Hello, I did read the FAQ on template(*), since I could not find an answer to my current issue I am posting here. I have tried to summarize my issue in the following code (**). Basically I am...
6
by: JDT | last post by:
Hi, Can we pass a member function in a class as a callback function? Someone instucted me that I can only use a static functon or a global function as a callback. Your help is appreciated. JD
8
by: Malciah | last post by:
I posted this on another site, but so far I've had no answers. So, I decided to try it here. -------------------------------------------------------- I've been learning C++ for about 6 weeks now,...
6
by: Gaijinco | last post by:
I'm trying to do a template class Node. My node.hpp is: #ifndef _NODE_HPP_ #define _NODE_HPP_ namespace com { namespace mnya { namespace carlos { template <typename T>
55
by: tonytech08 | last post by:
How valuable is it that class objects behave like built-in types? I appears that the whole "constructor doesn't return a value because they are called by the compiler" thing is to enable...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.