473,808 Members | 2,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class Templates, Pointers, and transferring data between class objects

36 New Member
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 2100
Soneji
36 New Member
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 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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 New Member
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 Recognized Expert MVP
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 New Member
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
1640
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 this is elsewhere in the newsgroup & please reply with links to threads or something? (I dont know what to look for :( ) (Terms are prob. all wrong as well :( ) The problem: I have a data structure represented by a class. Use a date class as an
9
4815
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 am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
9
2323
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 same type for a given instance of the class, but different types for different instances.) #include<set> using namespace std; template<class T>
12
1790
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; std::vector<AbstractBase*> vec; vec.push_back(&i); vec.push_back(&f);
7
1405
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
3466
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 trying to hide the `complexity` of template from the user interface. If you look at the code DataSet should be the object that my user manipulate. Unfortunately by doing so the object returned by DataSet::Get is a FloatingPt, so without the virtual...
6
3456
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
429
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, and I've been able to figure out the cause of pretty much every problem I've run into. This time, I'm at a loss. The book I'm learning from isn't the greatest in the world, and it hasn't given me a good explanation since chapter 6. (I'm in...
6
391
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
4001
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 built-in-like behavior for objects of class type. That leads to the "necessity" for the exception machinery so that errors from constructors can be handled. Is all that complexity worth it just to get built-in-like behavior from class objects? Maybe a...
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10114
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
9196
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
6880
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
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
2
3859
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
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.