C++: Key Points - Constructors

Purpose

Constructors have one purpose - to allow you to guarantee that objects are correctly initialized. The compiler will guarantee that your constructors are called, inserting constructor calls as necessary. This is a great leap in reliability over C programming where, if the programmer forgot to initialize something explicitly, it contained whatever garbage was in memory.

Three types - No-parameter (default), copy constructors, and all others. Only the first two have unexpected aspects.

1. No-parameter (default) constructors

2. Copy constructors

Questions

Assume A is a class.

Function definitions

A f(A x)   { return x;}
A g(A& x)  { return x;}
A& h(A& x) { return x;}

Questions

For each of the following function calls, how many times is the copy constructor called?

A a;
A b;

a = f(b);
a = g(b);
a = h(b);