473,473 Members | 2,292 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

default assignment operator

65 New Member
while assigning on object to another,
default assignment operator written by compiler
makes memberwise copying that why there isn't any problem with
types like (int ,double etc) but it cannot copy strings, these are ok.
what i dont understand is how it can manage assigning arrays.
let me explain with an example:

Expand|Select|Wrap|Line Numbers
  1. class myClass {
  2.   int val1;
  3.   char *str;
  4.   int array[5];
  5. };
  6.  
  7. myClass B;   // create object B
  8. myClass A=B;   // initialize object A with object B
  9.  
val1 --> A.val1= B.val1 this is valid and ok for me
str ---> A.str=B.str this is invalid and ok for me
array--> A.array=B.array this is valid but how? and why?
May 4 '07 #1
11 3998
Ganon11
3,652 Recognized Expert Specialist
This works because the arrays in each class are just variables. In this case, though, it's not a good idea to copy them like this. The value actually being stored in A.array and B.array are pointers - addresses in memory where the 5 integers will actually be stored. When you type A.array = B.array, you are giving A.array the same memory address that B.array was holding. Now A.array and B.array are pointing to the same memory.

But what happens when, say, B goes out of scope? It is de-allocated, and the memory pointed to by B.array is erased. But A.array is still pointing to that same place, and is now useless!

I can't seem to successfully post how you should go about this; stupid school computer. Perhaps one of my colleagues can finish my explanation.
May 4 '07 #2
AdrianH
1,251 Recognized Expert Top Contributor
This works because the arrays in each class are just variables. In this case, though, it's not a good idea to copy them like this. The value actually being stored in A.array and B.array are pointers - addresses in memory where the 5 integers will actually be stored. When you type A.array = B.array, you are giving A.array the same memory address that B.array was holding. Now A.array and B.array are pointing to the same memory.

But what happens when, say, B goes out of scope? It is de-allocated, and the memory pointed to by B.array is erased. But A.array is still pointing to that same place, and is now useless!

I can't seem to successfully post how you should go about this; stupid school computer. Perhaps one of my colleagues can finish my explanation.
Sorry Ganon, not quite right. The array is not stored on the seperatly, but is an aggregate item (C/C++ term, UML states this as a composite item. Grrr, just found out that UML uses different terms from C/C++ :(), so the entire array is copied.

If it were a pointer to an array (UML may state this as a aggregate association, though you can have something that is physicly seperated from the main object and still have a composition association) you would be correct in that only the pointer would be coped, just like the c-string that OP stated in his/her example. In which case, it would cause a problem when doing memory cleanup. If not done properly, you could have an object pointing at another that is not there (has been deleted by the other owning object).


Adrian
May 4 '07 #3
Ganon11
3,652 Recognized Expert Specialist
So because the array was declared with the braces [], it will be copied correctly? But if the array had been declared as a pointer, then what I said would hold true, right?
May 4 '07 #4
AdrianH
1,251 Recognized Expert Top Contributor
So because the array was declared with the braces [], it will be copied correctly? But if the array had been declared as a pointer, then what I said would hold true, right?
Except for the fact that [] are called brackets (I know its a detail, but I didn’t make the terminology ;). Further, {} are braces and () are parentheses.) yes.


Adrian
May 4 '07 #5
Ganon11
3,652 Recognized Expert Specialist
Hey, I'm a programmer, and I can typedef brackets into braces and vice versa! :P
May 4 '07 #6
stmfc
65 New Member
thnaks a lot, but i am still confused.
we cannot directly assign an array to another array,
but if we put the array in a class we can assign the class directly to another class (so the array is directly assigned too).
is not it bit strange?
May 7 '07 #7
AdrianH
1,251 Recognized Expert Top Contributor
thnaks a lot, but i am still confused.
we cannot directly assign an array to another array,
but if we put the array in a class we can assign the class directly to another class (so the array is directly assigned too).
is not it bit strange?
Strange? I guess, but in a nice way. ;)

You are right an array cannot be assigned to another array. But when it is wrapped up in a class/struct, it becomes just a bunch of individual objects that are member-wise copied. I cannot quote the reason from the C spec as to why this occurs, it just the way it is.


Adrian
May 7 '07 #8
weaknessforcats
9,208 Recognized Expert Moderator Expert
First of all this code crashes:
class myClass {
int val1;
char *str;
int array[5];
};

myClass B; // create object B
myClass A=B; // initialize object A with object B
The default assignment operator the compuiler uses is for the built-in types only.

In the case of the array member, this is a STACK variable. The name "array" is the address of element 0. So, the name "array" is a char*. The default assignment for a char* is to just copy the pointer. All that happens is:
Expand|Select|Wrap|Line Numbers
  1. A.array = B.array;
  2.  
meanng the only the ADDRESS of the array in B is copied.

BUT, the target array in A is also a STACK variable. You cannot change the address of a stack variable. You crash at this point.

You must copy the array element by element:

Expand|Select|Wrap|Line Numbers
  1. A::A(const B& rhs)
  2. {
  3.     for (int ctr=0; ctr< 5; ++ctr)
  4.     {
  5.          this->array[ctr] = rhs.array[ctr];
  6.     }
  7. }
  8.  
It makes no difference whatsoever whether [] were used or not. In C++ you can never copy arrays using an assignment operator. Things like this is precisely why the vector template was created.

The class member should be:
Expand|Select|Wrap|Line Numbers
  1. class myClass {
  2.   int val1;
  3.   char *str;
  4.   vector<int> array;
  5. };
  6.  
If you use a vector<int>, the orignal code works as written because the assignment operator for vector will do the copy.
May 7 '07 #9
AdrianH
1,251 Recognized Expert Top Contributor
First of all this code crashes:

The default assignment operator the compuiler uses is for the built-in types only.

In the case of the array member, this is a STACK variable. The name "array" is the address of element 0. So, the name "array" is a char*. The default assignment for a char* is to just copy the pointer. All that happens is:
Expand|Select|Wrap|Line Numbers
  1. A.array = B.array;
  2.  
meanng the only the ADDRESS of the array in B is copied.
Sorry but this is wrong. See up thread for an explanation.

For a simple example of this working try the following code:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct A
  5. {
  6.   int array[3];
  7. };
  8.  
  9. int main() {
  10.   A a = {{1,2,3}};
  11.   A b = a;
  12.   for (int i = 0; i < 3; ++i) {
  13.     cout << "a.array[" << i << "] = " << a.array[i] << endl;
  14.     cout << "b.array[" << i << "] = " << b.array[i] << endl;
  15.   }
  16.   return 0;
  17. }
As you will see, the assignment works.


Adrian
May 7 '07 #10
weaknessforcats
9,208 Recognized Expert Moderator Expert
As you will see, the assignment works.
Yes, I do. I got sidetracked by Visual Studio.NET which crashes because the A array is not initialized in the original code. You initialized it to 1,2,3. Visual Studio.NET crashes if you use uninitialized variables.
May 8 '07 #11
AdrianH
1,251 Recognized Expert Top Contributor
Yes, I do. I got sidetracked by Visual Studio.NET which crashes because the A array is not initialized in the original code. You initialized it to 1,2,3. Visual Studio.NET crashes if you use uninitialized variables.
I wouldn't be surprised if Visual Studio crashes if you sneeze in a certain way. ;)

Actually, if you start doing things with undefined variables, the result is undefined so it is possible that it got overlooked.


Adrian
May 8 '07 #12

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

Similar topics

18
by: Dan Cernat | last post by:
Hi there, A few threads I had a little chat about default values. I am starting this thread because I want to hear more opinions about the default values of function parameters. Some say they...
10
by: cppaddict | last post by:
Hi, I am writing a program and needs to know one of its object members before it can be initialized. It doesn't really matter for my question (which a C++ question, not a windows question), but...
4
by: Steven T. Hatton | last post by:
I mistakenly set this to the comp.std.c++ a few days back. I don't believe it passed the moderator's veto - and I did not expect or desire anything different. But the question remains: ISO/IEC...
4
by: moleskyca1 | last post by:
Hi, In a recent discussion, some of us were in disagreement about the functions the C++ compiler generates. How many functions are generated by the compiler when you declare: class Foo { };...
5
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
3
by: Ganesh Rajaraman | last post by:
Hi, This is the program that i am trying. class A { public: A() { cout<<"Default Constructor"<<endl;
23
by: Jess | last post by:
Hello, I understand the default-initialization happens if we don't initialize an object explicitly. I think for an object of a class type, the value is determined by the constructor, and for...
43
by: JohnQ | last post by:
Are a default constructor, destructor, copy constructor and assignment operator generated by the compiler for a struct if they are not explicitely defined? I think the answer is yes, because...
9
by: George2 | last post by:
Hello everyone, I am wondering the default implementation of assignment operator (e.g. when we do not implement assignment operator in user defined class, what will be returned? temporary...
9
by: puzzlecracker | last post by:
From my understanding, if you declare any sort of constructors, (excluding copy ctor), the default will not be included by default. Is this correct? class Foo{ public: Foo(int); // no...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
1
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...
0
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...
0
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,...
0
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...
0
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 ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.