Copy Constructors (C++) Flashcards

1
Q

What happens if you don’t have an initialization list when you write a copy constructor for a derived class?

A

The default constructor of the base class is invoked and sets everything to zero instead invoking the base class’s copy constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When do problems with shallow copying occur?

A
  1. When there is dynamic memory being copied.
  2. Initializing an object with the value of another:
    class obj1; class obj2(obj1);
  3. pass or return by value
  4. Assign one object to another using the assignment operator
    obj1 = obj2;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a shallow versus deep copy?

A

Shallow: data members of one object are copied into another without taking dynamic memory into account. A shallow copy is “automatic” and is also referred to as a “memberwise” copy.

Deep: Deep copy is for when dynamic memory pointed to by the data members is duplicated and the contents of the memory is copied. A copy constructor that performs a deep copy must be explicitly made.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why doesn’t Java have the same copy constructor requirements?

A

Java does not pass an object by value so it does not require making a copy of the entire contents of an object. There is only pass by reference and just makes a copy of the address.

In C++ you’re forced to make copies because of the memory issues with raw pointers. Makes a copy of the object’s state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the three instances for a constructor (default or copy) getting invoked?

A
  1. Pass by value
  2. Return by value
  3. Create a new object of that class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When is a constructor invoked (General)?

A

A constructor is invoked after memory is created. If an object has been formed, memory has been allocated and needs to be initialized. This is why it is called an initialization list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

If only a derived class has dynamic memory, how does the parent’s data get copied?

A

Need to create an initialization list with the copy constructor if a derived class manages dynamic memory. This will activate the parent’s automatic copy constructor.

If an initialization list is not made then the default constructor gets invoked.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly