Dynamic Stack  «Prev  Next»
Lesson 5Defining a copy constructor
Objective Add a constructor to the ch_stack class based on a supplied function prototype.
In C++, if the copy constructor is not present, then these operations default to member-by-member initialization of value.
It is appropriate for the class to explicitly define its own copy constructor, even though the compiler provides a default copy constructor.

Here is the copy constructor for ch_stack:
//Copy constructor for ch_stack of characters
ch_stack::ch_stack(const ch_stack& str):
   max_len(str.max_len),top(str.top)
{
   s = new char[str.max_len];
   assert(s);
   memcpy(s, str.s, max_len);
}

Add a constructor to the ch_stack class based on a supplied function prototype.

Copy Constructors in C++

A constructor that takes as argument a reference to an object of the same class is termed a copy constructor. A copy constructor is used to create a copy, or clone, of a value:
String first("Fred");
String second(first);
// second is initialized from first using copy constructor
String third = first; // Also uses copy constructor
The body of the copy constructor must do whatever is necessary to copy the value from the argument. In our example every String value manages its own dynamically allocated buffer. Therefore the copy constructor creates and initializes a new area:
String::String(const String& right)
{
len = right.length();
buffer = new char[len + 1];
for (int i = 0; i < len; i++)
buffer[i] = right[i];
buffer[len] = '\0';
}

Copy constructors are invoked whenever a new object needs to be created as an exact copy of an existing object. This happens, for example, when an object is passed as an argument to a function that has declared a value parameter.
void print_line(String a)
{
cout <<  a;
a = "\n"; // Function modifies parameter variable
cout << a;
}
String name("Fred");
print_line(name); // Argument is initialized by copy constructor
cout << name;

Adding Constructor to Stack - Exercise

Click the Exercise link below to add a constructor to the ch_stack class based on a supplied function prototype.
Adding Constructor to Stack - Exercise