donderdag 5 juli 2007

impicit type cast to class object

In C++, any constructor that takes a single argument acts as a blueprint for converting a value of that argument type to the class type. Thus the constructor

Stonewt(double lbs); // template for double-to-Stonewt conversion

serves as instructions for converting a type double value to a type Stonewt value, That is, you can write code like the following:

Stonewt myCat; // create a Stonewt object
myCat = 19.6; // use Stonewt(double) to convert 19.6 to Stonewt

The program uses the Stonewt(double) constructor to construct a temporary Stonewt object, using 19.6 as the initialization value. Then memberwise assignment copies the contents of the temporary object into myCat. This process is termed an implicit conversion because it happens automatically, without the need of an explicit cast.

Only a constructor that can be used with just one argument works as a conversion function. The constructor

Stonewt(int stn, double lbs);

has two arguments, so it cannot be used to convert types.

REMEMBER
A c++ constructor that contains one argument defines a type conversion from the argument type to the class type. If the constructor is qualified with the keyword explicit, the constructor is used for explicit conversions only; otherwise it is also used for implicit conversions.

maandag 2 juli 2007

introducing Friends

As you've seen, C++ controls access to the private portions of a class object. Usually, public class methods serve as the only access, but somethimes this restriction is too rigid to fit particular programming problems. In such cases, C++ provides another form of access: the friend.
Friends come in three varieties:

- Friend functions
- Friend classes
- Friend member functions

By making a function friend to a class, you allow the function the same access privileges that a member function of the class has. We'll look into friend functions now, leaving the other two varieties to another blog.

A = 2.75 * B; // cannot correspond to a member function

Thus the compiler could match this expression to the following nonmember function call:

A = operator*(double m, const Time & t);

With the nonmember overloaded operator function, the left operand of an operator expression corresponds to the first argument of the operator function, and the right operand corresponds to the second argument. Meanwhile, the original member function handles operands in the opposite order--that is , a Time value multiplied by a double value.

Using a nonmember function solves the problem of getting the operands in the desired order (first double and then time), but it raises a new problem: Nonmember functions can't directly access private data in a class. Well, at least ordinary nonmember functions lack access. But there is a special category of nonmember functions, called friends that can access private members of a class.

Creating Friends
The first step toward creating a friend function is to place a prototype in the class declaration and prefix the declaration with the keyword friend:

friend Time operator*(double m, const Time & t); // goes in class declaration

This prototype has two implications:
- Although the operator*() function is declared in the class declaration, it is not a member function. SO it isn't invoked by using the membership operator
- Although the operator*() function is not a member function, it has the same access rights as a member function.

The second step is to write the function definition. Because it is not a member function, you don't use the Time:: qualifier. Also, you don't use the friend keyword in the definition. The definition should look like this:

Time operator*(double mult, const Time & t) // friend not used in definition
{
Time result;
long totalminutes = t.hours * mult * 60 + t.minutes * mult;
result.hours = totalminutes / 60;
result.minutes = totalminutes % 60;
return result;
}

With this declaration and definition, the statement
A = 2.75 * B;

translates to
A = operator*(2.75, B);

and invokes the nonmember friend function you just defined.

In short, a friend function to a class is a nonmember function that has the same access rights as a member function.

Remember:
A nonmember version of an overloaded operator function require as many formal parameters as the operator has operands. A member version of the same operator requires one fewer parameter because one operand is passed implicitly ad the invoking object, the this pointer ;)

operator overloading

total = coding.operator+(fixing); // function notation

But naming the method operator+() also lets you use operator notation:

total = coding + fixing; // operator notation

Either notation invokes the operator+() method. Note that with the operator notation, the object to the left of the operator (coding in this case) is the invoking object, and the object to the right (fixing in this case) is the one passed as an argument.

Can you add more than two objects? For example, if t1, t2, t3 and t4 are all Time objects, can you do the following?

t4 = t1 + t2 + t3; // valid?

The way to answer this is to consider how the statement gets translated into function calls.
Because addition is a left-to-right operator, the statement is first translated to this:

t4 = t1.operator+(t2 + t3); // valid?

Then the function argument is itself translated to a function call, giving the following:

t4 = t1.operator+(t2.operator+(t3)); // valid? YES

The function call t2.operator+(t3) returns a Time object that represents the sum of t2 and t3. This object then becomes the object of the t1.operator+() function call, and that call returns the sum of t1 and the Time object that represents the sim of t2 and t3. In short, the final return value is the sum of t1, t2 and t3, just as desired.

zondag 1 juli 2007

An Array of Objects

Often, as with the Stock examples, you want to create several objects of the same class. You can create separate object variables, as the examples have done so far in this blog, but it might make more sense to create an array of objects.

Stock mystuff[4]; // creates an array of 4 stock objects

Recall that a program always calls the default class constructor when it creates class objects that aren't explicitly initialized. This declaration requires either that the class explicitly define no constructors at all, in which case the implicit do-nothing default constructor is used, or. as in this case, that an explicit default constructor be defined. Each element--mystuff[0], mystuff[1], and so on--is a Stock object and thus can be used with the Stock methods:

mystuff[0].update(); // apply update() to 1st element
mystuff[3].show(); // apply show() to 4th element
Stock tops = mystuff[2].topval(mystuff[1]);
// compare 3rd and 2nd elements

You can use a constructor to initialize the array elements, In that case, you have to call the constructor for each individual element:

const int STKS = 4;
Stock stocks[STKS] = {
Stock("NanoSmart", 12,5, 20),
Stock("Boffo Objects", 200, 2.0),
Stock("Monolithic Obelisks", 130, 3.25),
Stock("Fleep Enterprises", 60, 6.5)
};

Here the code uses the standard form for initializing an array: a comma-seperated list of values enclosed in braces. In this case, a call to the constructor method represents each value. If the class has more than one constructor, you can use different constructors for different elements:

const int STKS = 10;
Stock stocks[STKS] = {
Stock("NanoSmart", 12.5, 20),
Stock(),
Stock("Monolithic Obelisks", 130, 3.25),
};

This initializes stock[0] and stocks[2] using the Stock(const char * co, int n, double pr) constructor and stocks[1] using the Stock() constructor. Because this declaration only partially initializes the array, the remaining seven members are initialized using the default constructor.

The scheme for initializing an array of objects still initially use the default constructor to create the array elements. Then the constructors in the braces create temporary objects whose contents are copied to the array/vector. Thus a class must have a default constructor if you want to create arrays of class objects.

The special pointer called 'this'

The C++ solution to not able to return the object that invokes a member function call is the special pointer "this". The this pointer points to the object used to invoke a member function. (Basically, this is passed as a hidden argument to the method.) Thus the function call stock1.topval(stock2) sets this to the address of the stock1 object and makes that pointer available to the topval() method.
Similarly, the function call stock2.topval(stock1) sets this to the address of the stock2 object. In general, all class methods have a this pointer set to the address of the object that invokes the method. Indeed, total_val in topval() is just a shorthand notation for this->total_val. (Recall from earlier blogs that you use the -> operator to access structure members via a pointer. The same is true for class members.)

The this pointer
Each member function, including constructors and destructors, has a this pointer. The special property of the this pointer is that it points to the invoking object. If a method needs to refer to the invoking object as a whole, it can use the expression *this. Using the const qualifier after the function argument parentheses qualifies this as being const; in that case, you can't use this to change the object's value.

What you want to return, however is not this, because this is the address of the object. You want to return the object itself, and that is symbolized by *this. (Recall that applying the dereference operator * to a pointer yields the value to which the pointer points.) Now you can complete the method definition by using *this as an alias for the invoking object:

const Stock & Stock::topval(const Stock & s) const
{
if (s.total_val > total_val)
return s; // argument object
else
return *this; // invoking object
}

The fact that the return type is a reference means that the returned object is the invoking object itself, rather than a copy passed by the return mechanism.

Destructors

When you use a constructor to create an object, the program undertakes the responsibolity of tracking that object until it expires. At that time, the program automatically calls a special member function bearing the formidable title destructor The destructor should clean up any debris, so it actually serves a useful purpose. For example, if your constructor uses new to allocate memory, the destructor should use delete to free that memory.
In case of the Stock class, the Stock constructor doesn't do anything fancy like using new, so the Stock class destructor doesn't really have any tasks to perform. In such a case, you can simply let the compiler generate an implicit, do-nothing destructor, which is exactly what the first version of the Stock class does.

Like a constructor, a destructor has a special name: It is formed from the class name preceded by a tilde(~). Thus the destructor for the Stock class is called ~Stock. Also, like a constructor, a destructor can have no return value and has no declared type. Unlike a constructor, a destructor must have no arguments. Thus the prototype for a Stock destructor must be this:

~Stock();

Because a Stock destructor has no vital duties, you can code it as a do-nothing function:

Stock::~Stock()
{
}

However, just so that you can see when the destructor is called, you can code it this way:

Stock::~Stock() // class destructor
{
cout << "Bey, " << company << "!\n";
}

When should a destructor be called? The compiler handles this decision; normally your code shouldn't explicitly call a destructor.
If you create a static storage class object, its destructor is called automatically when the program terminates. If you create an automatic storage class object, as the examples have been doing, its destructor is called automatically when the program exits the block of code in which the object is defined.
If the object is created using new, it resides in heap memory, or the free store, and its destructor is called automatically when you use delete to free the memory.
Finally, a program can create temporary objects to carry out certain operations; in that case, the program automatically calls the destructor for the object when it has finished using it.

Because a destructor is called automatically when a class object expires, there ought to be a destructor. If you don't provide one, the compiler implicitely declares a default constructor and, if it detects code that leads to the destruction of an object, it provides a definition for the destructor.

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.