copying objects c++

Here is a code:

1
2
3
4
5
6
7
  // stack is a class
  // st1 is an object that contains something
  // st2 is a newly created object
  stack st1;
  // ...  
  stack st2;
  st2 = st1;


Q1. Is it a good idea to copy one object into another by st2 = st1? Or is it better to have a copy constructor for it?

Ex.
 
  stack st2(st1);




Q2. My professor says "use st2 = st1; when a class is working with dynamic memory". Why? I don't understand what he means.


Q1. Normally it shouldn't make any differences. It depends on how the constructor/asignment operator is implemented.

Q2. See: Q1.

See the rule of three:

http://en.cppreference.com/w/cpp/language/rule_of_three

It means that both the copy constructor and the operator= should be implemented [the same way]. So that it does not make a difference whether you call the one or the other.

In your case: Maybe the copy constructor is missing?
As a general rule I would not expect to see a default constructor immediately followed by assignment. Instead I would expect

stack st2(st1);

or

stack st2 = st1; // also calls copy constructor

Your professor's comment makes no sense to me.

Andy
@coder777,

thanks for your help.
--------------------------------------------------------
@andywestken,

I realized that the I can create my copy constructor to do a deep copy, and also that st2 = st1 is right even without having assignment operator (operator=()), but it is shallow copy only.

Now I have another question for you, so if I do st2 = st1, is there any way I can make it do a deep copy instead of shallow copy? Does it have to do with the way I have to implement the assignment operator?

Here is an implementation of my assignment operator:
Does this do deep copy for st2 = st1?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cs& cs::operator=(const cs& copy){
    // check for self-assignment
    if(this == &copy){
        return *this;
    }

    // shallow copy for variables
    maxSize = copy.arraySize;
    currentSize = copy.currentSize;

    // array is a pointer, so check for non-null
    if(copy.array){
        // allocate memory
        array = new string[arraySize];

        for(int i = 0; i < arraySize; i++){
            array[i] = copy.array[i];
        }        
    }
    // if non-null, set to null
    else{
        array = NULL;
    }                               

    return *this;
}


Last edited on
Topic archived. No new replies allowed.