FAQ 2.06 What are the basics of constructing objects using explicit parameters?

graphics/new_icon.gif

Constructors are special member functions that are called to initialize an object. If parameters are needed, the parameters can be supplied in the parentheses, (). If no parameters are needed on a local object, parentheses must not be provided. Here is an example:

 #include "Car.hpp" void f() {   Car a;                                             <-- 1   Car b(100, 73);                                    <-- 2   // ... } int main() {   f(); } 

(1) 1: Create a "default" Car object

(2) 2: Pass explicit parameters to Car's constructor

When control flows over line 1, a local Car object is created and initialized by the class's default constructor. The default constructor is the constructor that can be called with no parameters (see FAQ 20.08).

When control flows over line 2, another local Car object is created and initialized, this time by passing two int parameters to a constructor of class Car. The parameters (100, 73) are presumably used to set up the object (e.g., initial values for various state variables). Line 1 and line 2 probably call different constructors (but see FAQ 2.04 on default parameters).

Note that in the following example b is not a Car object. Instead b is a function that returns a Car by value.

 void g() {   Car a;                                             <-- 1   Car b();                                           <-- 2 } 

(1) a is a Car object

(2) b is not a Car object!



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