int i = 17; … int j = i; // copy the value of i to j
class C {
…
private:
int i;
double d;
int arr[100];
int *ip;
};
…
C c1(…);
C c2 = c1; // copy the data members of c1 to c2
class C {
C(const C &c) : capacity(c.capacity), arr(new int[c.capacity]) {…} // ooops … forgot to set size to 0
private:
int *arr;
int capacity, size;
};
Person class
might accept a Name object and an age integer as its constructor arguments; or a Rational class would accept
numerator and denominator arguments to its constructor. Such constructors would not carry over from class to class — the information
passed to the constructor is specific to the class' application space.
Rational class only supplied the 2-arg constructor, one could not create Rational with only a numerator, or NO arguments, regardless of whether such initialization
would make sense. In other words, the only legal initialization of the object is what the constructor designers offer.
Note: for this discussion, we're assuming a class C.
C())
class Person {
public:
Person(const Name &name, int age);
…
};
it is clear that the designer of Person requires a Name and age in order to initialize a Person object. Furthermore,
had they wished a default initialization be permitted, they would have supplied a default constructor.
C(const C &))C c1(…); C c2 = c1;
void f(C c); … C c1(&hellip_; … f(c1);
C f(); … C c1(&hellip_; … c1 = f();
class C {
C(int capacity) : capacity(capacity), arr(new int[capacity]), soze(0) {}
…
private:
int *arr;
int capacity, size;
};
…
C c1(…);
…
C c2 = c1; // memberwise copy will only copy the pointer (shallow copy), we probably want to make a copy of the dynamic array
C & operator =(const C &))