#include "Car.hpp" <-- 1 void f() { Car a; <-- 1 a.startEngine(); <-- 2 a.tuneRadioTo("AM", 770); <-- 3 } <-- 4 int main() { f(); }
When control flows over the line labeled 1: Create an object, the runtime system creates a local (auto) object of class Car. The object is called a and can be accessed from the point where it is created to the } labeled 4: Destroy the object. When control flows over the line labeled 2: Call a member function, the startEngine() member function (a.k.a. method) is called for object a. The compiler knows that a is of class Car so there is no need to indicate that the proper startEngine() member function is the one from the Car class. For example, there could be other classes that also have a startEngine() member function (Airplane, LawnMower, and so on), but the compiler will never get confused and call a member function from the wrong class. When control flows over the line labeled 3: Call another member function, the tuneRadioTo() member function is called for object a. This line shows how parameters can be passed to member functions. When control flows over the line labeled 4: Destroy the object, object a is automatically destroyed. If the Car class has some special cleanup activities that need to take place when an object goes away, the writer of the class would include a destructor in the class and the runtime system would automagically call the destructor (dtor) when the object goes away; see FAQ 20.03. Local objects such as a are sometimes called automatic objects or stack objects, and they are said to go out of scope at the } line. UML uses the following notation to show a class Car that contains member functions startEngine() and tuneRadioTo(): |