FAQ 2.05 What are the basics of local (auto) objects?

graphics/new_icon.gif

C++ extends the variable declaration syntax from built-in types (e.g., int i;) to objects of user-defined types. The syntax is the same: TypeName VariableName. For example, if the header file "Car.hpp" defines a user-defined type called Car, objects (variables) of class (type) Car can be created:

 #include "Car.hpp"                                   <-- 1 void f() {   Car a;                                             <-- 1   a.startEngine();                                   <-- 2   a.tuneRadioTo("AM", 770);                          <-- 3 }                                                    <-- 4 int main() {   f(); } 

(1) Define class Car

(1) 1: Create an object

(2) 2: Call a member function

(3) 3: Call another member function

(4) 4: Destroy the object

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():

graphics/02fig01.gif



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net