zondag 1 juli 2007

Class Constructors

At this point, you need to do more with the Stock class. There are certain standard functions, called constructors and destructors, that you should normally provide for a class.

One of C++'s aims is to make using class objects similar to using standard types. However, the code provided so far in this chapter doesn't let you initialize a Stock object the way you can an ordinary int or struct. That is, the usual initialization syntax doesn't carry over for the Stock type:

int year = 2001; // valid initialization
struct thing
{
char * pn;
int m;
};
thing amabob = {"wodget", -23}; // valid initialization
Stock hot = {"Sukie's Autos, Inc.", 200, 50.25}; // NO! compile error

The reason you can't initialize a Stock object this way is because the data parts have private access status, which means a program cannot access the data members directly. As you have seen, the only way a program can access the data members is through a member function.
Therefor, you need to devise an appropriate member function if you're to succeed in initializing an objects. (You could initialize a class onject as just shown if you made the data members public instead of private, but making the data public goes against one of the main justifications for using classes: data hiding.)

In general, it's best that all objects be initialized when they are created. For example, consider the following code:

Stock gift;
gift.buy(10, 24.75);

With the current implementation of the Stock class, the gift object has no value for the company member. The class design assumes that the user calls acquire() before calling any other member functions, but there is no way to enforce that assumption.

One way around this difficulty is to have objects initialized automatically when they are created. To accomplish this C++ provides for special member functions, called class constructors especially for constructing new objects and assigning values to their data members.
The name of a constructor is the same as the class name. For example, a possible constructor for the Stock class is a member function called Stock(). The constructor prototype and header file hace an interesting property: Although the constructor has no return value, it's not declared type void. In fact, a constructor has no declared type.

In the example of the Stock class, the constructor could look like this:
// constructor prototype with some default arguments
Stock(const char * co, int n = 0; double pr = 0.0);

The first argument is a pointer to the string that is used to initialize the company character array member. The n and pr arguments provide values for the shares and share_val members. Note that there is no return type. The prototype goes in the public section of the class declaration.

Next, here's one possible definition for the constructor:
// constructor definition
Stock::Stock(const char* co, int n, double pr)
{
std::strncpy(company, co, 29);
company[29] = '\0';

if (n < 0)
{
std::cerr << "Number of shares can't be negative; ";
<< company << " shares set to 0.\n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}

This code is the same code that you used for the acquire() function earlier in this chapter. The difference is that in this case, a program automatically invokes the constructor when it declares an object.

C++ provides two ways to initialize an object by using a constructor. The first is to call the constructor explicitly:

Stock food = Stock("World Cabbage", 250, 1.25);

The second way is to call the constructor implicitly:

Stock garment("Furry Mason", 50, 2.5);

C++ uses a class constructor whenever you create an object of that class, even when you use new for dynamic memory allocation. Here's how to use the constructor with new:

Stock *pstock = new Stock("Electroshock Games", 18, 19.0);

Default Constructors
A default constructor is a constructor that is used to create an object when you don't provide explicit initialization values. That is, it's a constructor that is used for declarations like this:

Stock stock1; // uses the default constructor

If you fail to provide any constructors, C++ automatically supplies the default constructor. It's an implicit version of a default constructor, and it does nothing.
For the Stock class, the default constructor would look like this:

Stock::Stock() {}

if you provide a constructor, then C++ does NOT create the default constructor automatically, you have to provide yourself a default constructor!

You can define a default constructor two ways. One is to provide default values for all the arguments to the existing constructor:

Stock(const char* co = "Error", int n = 0; double pr = 0.0);

The second is to use function overloading to define a second constructor, one that has no arguments:

Stock();

You can have only one default constructor, so be sure that you don't do both.

Actually, you should usually initialize objects in order to ensure that all members begin with known, reasonable values. Thus, a default constructor typically provides implicit initialization for all member values. For example, this is how you might define one for the Stock class:

Stock::Stock() // default constructor
{
std::strcpy(company, "no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}

When you design a class, you should usually provide a default constructor that implicitly initializes all class members

After you've used either method(no arguments or default values for all arguments) to create the default constructor, you can declare object variables without initializing them explicitly:

Stock first; // calls default constructor implicitly
Stock first = Stock(); // calls it explicitly
Stock *prelief = new Stock; // calls it implicitly

However, you shouldn't be misled by the implicit form of the nondefault constructor:
Stock first("Concrete Conglomerate"); // calls constructor
Stock second(); // declares a function
Stock third; // calls the default constructor

The first declaration here calls the nondefault constructor--that is, the one that takes arguments. The second declaration states that second() is a function that returns a Stock object. When you implicitly call the default constructor, you don't use parentheses.

Geen opmerkingen: