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.
donderdag 5 juli 2007
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 ;)
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.
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.
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.
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.
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.
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.
zaterdag 30 juni 2007
objects and classes I
The following are the most OOP (Object Oriented Programmin) features:
- Abstraction
- Encapsulation and data hiding
- Inheritance
- Reusability of code
I will now summarize what I read about classes and I should remember.
The class is the single most important C++ enhancement for implementing these features and tying them together!
Procedural and Object-Oriented Programming
In short, with a procedural approach, you first concentrate on the procedures you will follow and then think about how to represent the data.
In short, with an OOP approach, you concentrate on the object as the user perceives it, thinking about the data you need to describe the object and the operations that will describe the user's interaction with the data. After you develop a description of that interface, you move on to decide how to implement the interface and data storage. Finally, you put together a program to use your new design.
Abstraction and Classes
In computing, abstraction is the crucial step of representing information in terms of its interface with the user. That is, you abstract the essential operational features of a problem and express a solution in those terms.
In the softball example (sorry, not showen here), the interface describes how the user initializez, updates and display the data. From abstraction, it is a short step to the user-defined type, which in C++ is a class design that implements the abstract interface.
What is a type?
At first you tend to think of a datatype in terms of its appearance--how it is stored in memory.
A char, for example is 1 byte of memory, and a double is often 8 bytes of memory.
But a little reflection leads you to conclude that a data type is also defined in terms of operations that can be performed on it.
For example, the int type can use all the arithmetic operations. You can add, subtract, multiply, and divide integers. You can also use the modulus operator (%) with them.
On the other hand, consider pointers. A pointer might very well require the same amount of memory as an int. It might even be represented internally as an integer. But a pointer doesn't
allow the same operations that an integer does. You can't for example, multiply two pointers by eachother.
Thus when you declare a variable as an int or as a pointer-to-float, you're not just allocating memory--you are also establishing which operations can be performed with the variable.
In short, specifying a basic type does three things:
- It determines hwo much memory is needed for a data object.
- It determines how the bits in memory are interpreted. (A long and a float might use the same number of bits in memory, but they are translated into numeric values differently.)
- It determines what operations, or methods, can be performed using the data object.
For built-in types, the information about operations is built in to the compiler. But when you define a user-defined type in C++, you have to provide the same kind of information yourself.
In exchange for this extra work, you gain the power and flexibility to custom fit new data types to match real-world requirements.
Classes in C++
A class is a C++ vehicle for stranslating an abstraction to a user-defined-type. It combines data representation and methods for manipulating that data into one neat package.
To define a class, Generally, a class specification has two parts:
- A class declaration, which describes the data component, in terms of data members, and the public interface, in terms of member functions, termed methods
- The class method definitions, which describe how certain class member functions are implemented
Roughly speaking, the class declaration provides a class overview, whereas the method definitions supply the details.
What is an Interface?
For classes, we speak of the public interface. In this case, the public is the program using the class, the interacting system consists of the class objects, and the interface consists of the methods provided by whoever wrote the class. The interface enables you, the programmer, to write code that interacts with class objects, and thus it enables the program to use the class objects. For example, to find the number of characters in a string object, you don't open up the object to what is inside; you just use the size() method provided by the class creators. It turns out that the class design denies direct access to the public user. But the public is allowed to use the size() method. The size() method, then, is part of the public interface between the user and a string class object.
Similarly, the getline() method is part of the istream class public interface.
If you want a more personal relationship, instead of thinking of the program using a class as the public user, you can think of the person writing the program using the class as the public user. But in any case, to use a class, you need to know its public interface; to write a class, you need to create its public interface.
The keywords private public describe access control for class members.
Any program that uses an object of a particular class can access the public portions directly. A program can access the private members of an object only by using the public member functions. Thus, the public member functions act as go-betweens between a program and an object's private members; they provide the interface between object and program.
data hiding, this isulation of data from direct access by a program is called data hiding.
A class design attempts to separate the public interface from the specifics of the implementation. The public interface represents the abstraction component of the design.
Gathering the implementation details together and separating them from the abstraction is called encapsulation. Data hiding (putting data into the private section of a class) is an instance of encapsulation, and so hiding functional details of an implementation in the private section.
Another example of encapsulation is the usual practice of placing class function definitions in a seperate file from the class declaration.
Note that data hiding not only prevents you form accessing data directly, but it also absolves you (in the roll as user of the class) from needing to know how the data is represented.
For example a class show() member can display the total value of a holding, this value can be stored as part of an object, or it can be calculated when needed.
From the standpoint of the user, it makes no difference which approach is used.
What you need to know is what the different member functions accomplish; that is, you need to know what kinds of arguments a member function takes and what kind of return value it has.
The principle is to separate the details of the implementation from the design of the interface.
If you later find a better way to implement the data representation or the details of the member functions, you can change those details without changing the program interface, and that makes programs much easier to maintain.
Implementing Class Member Functions
You still have to create the second part of the class specification: providing code for those member functions represented by a prototype in the class declaration. Member function definitions are much like regular functions. Each has a function header and a function body. Member function definitions can have return types and arguments. But they also have two special characteristics:
- When you define a member function, you use the scope-resolution operator (::) to identify the class to which the function belongs
- Class methods can access the private components of the class
First, the function header for a member function uses the scope-resolution operator (::) to indicate to which class the function belongs.
See this example:
void Stock::update(double price)
This notation means you are defining the update() function that is member of the Stock class.
Thus, the scope-resolution operator resolves the identity of the class to which a method definition applies. We say that the identifier update() has class scope. Other member functions of the Stock class can, if necessary, use the update() method without using the scope-resolution operator. That is because they belong to the same class, making update() in scope.
The second special characteristic of methods is that a method can access the private members of a class. For example, the show() method can use code like this:
cout << "Company: " << company
<< " Shares: " << shares << endl;
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << endl;
Where all those variables are in the private section of the class.
Here company, shares, and so on are private data members of the Stock class. If you try to use a nonmember function to access these data members, the compiler stops you cold in your tracks. (However, friend functions, later discussed provide an exception).
Which Object Does a Method Use?
Now we come to one of the most important aspects of using objects: how you apply a class method to an object. Code such as
shares += num;
uses the shares member of an object. But which object? That is an excellent question! To answer it, first consider how you create an object. The simplest way is to declare class variables:
Stock kate, joe;
This creates two objects of the Stock class, one named kate and one named joe.
Next, consider how to use a member function with one of these objects. The answer is, as with structures and structure members, is to use the membership operator:
kate.show(); // the kate object calls the member function
joe.show(); // the joe object calls the member function
The first call here invokes show() as a member of the kate object. This means the method interprets shares as kate.shares and share_val as kate.share_val. Similarly, the call joe.show() method interprets shares and share_val as joe.shares and joe.share_val respectively.
Each new object you create contains storage for its own internal variables, the class members. But all objects of the same class share the same set of class methods, with just one copy of each method.
Suppose, for example, that kate and joe are Stock objects. In that case, kate.shares occupies one chunk of memory and joe.shares occupies a second chunk of memory. But kate.show() and joe.show() both invoke the same method--that is, both execute the same block of code. They just apply the code to different data. Calling a member function is what some OOP languages term sending a message. Thus, sending the same message to two different objects invoke the same method but applies it to two different objects.
When the Stock class works as you want it to, you can use it as a user-defined type in other programs. The critical point in using the new type is to understand what member functions do;
You shouldn't have to think about the implementation details.
The Client/Server Model
OOP programmers often discuss program design in terms of a client/server model. In this conceptualization, the client is the program that uses the class. The class declaration, including the class methods, constitude the server, which is a resource that is available to the programs that need it. The client uses the server through the publicly defined interface only. This means that the client's only responsibility, and, by extension, the client's programmer's only responsibility, is to knwo that interface. The server's responsibility, and by extension, the server's designer's responsibility, is to see that the server reliably and accurately performs according to that interface. Any changes the server designer makes to the class design should be to details of the implementation, not to the interface. This allows programmers to improve the client and the server independently of each other, without changes in the server having unforseen repercussions on the client's behavior.
Full Qualified Name
char * Bozo::Retort()
The full, or qualified name of the above funtion is: Bozo::Retord(). The name Retort(), on the other hand, is an abbreviation of the qualified name, and it can be used only in certain circumstances, such as in the code for the class methods.
To create an object, which is a particular example of a class, you use the class name as if it where a type name:
Bozo bozetta;
This works because a class is a user-defined type.
You invoke a class member function, or method, by using a class object. You do so by using the dot membership operator:
This invokes the Retort() member function, and whenever the code for that function refers to a particular data member, the function uses the value that member has in the bozetta object.
- Abstraction
- Encapsulation and data hiding
- Inheritance
- Reusability of code
I will now summarize what I read about classes and I should remember.
The class is the single most important C++ enhancement for implementing these features and tying them together!
Procedural and Object-Oriented Programming
In short, with a procedural approach, you first concentrate on the procedures you will follow and then think about how to represent the data.
In short, with an OOP approach, you concentrate on the object as the user perceives it, thinking about the data you need to describe the object and the operations that will describe the user's interaction with the data. After you develop a description of that interface, you move on to decide how to implement the interface and data storage. Finally, you put together a program to use your new design.
Abstraction and Classes
In computing, abstraction is the crucial step of representing information in terms of its interface with the user. That is, you abstract the essential operational features of a problem and express a solution in those terms.
In the softball example (sorry, not showen here), the interface describes how the user initializez, updates and display the data. From abstraction, it is a short step to the user-defined type, which in C++ is a class design that implements the abstract interface.
What is a type?
At first you tend to think of a datatype in terms of its appearance--how it is stored in memory.
A char, for example is 1 byte of memory, and a double is often 8 bytes of memory.
But a little reflection leads you to conclude that a data type is also defined in terms of operations that can be performed on it.
For example, the int type can use all the arithmetic operations. You can add, subtract, multiply, and divide integers. You can also use the modulus operator (%) with them.
On the other hand, consider pointers. A pointer might very well require the same amount of memory as an int. It might even be represented internally as an integer. But a pointer doesn't
allow the same operations that an integer does. You can't for example, multiply two pointers by eachother.
Thus when you declare a variable as an int or as a pointer-to-float, you're not just allocating memory--you are also establishing which operations can be performed with the variable.
In short, specifying a basic type does three things:
- It determines hwo much memory is needed for a data object.
- It determines how the bits in memory are interpreted. (A long and a float might use the same number of bits in memory, but they are translated into numeric values differently.)
- It determines what operations, or methods, can be performed using the data object.
For built-in types, the information about operations is built in to the compiler. But when you define a user-defined type in C++, you have to provide the same kind of information yourself.
In exchange for this extra work, you gain the power and flexibility to custom fit new data types to match real-world requirements.
Classes in C++
A class is a C++ vehicle for stranslating an abstraction to a user-defined-type. It combines data representation and methods for manipulating that data into one neat package.
To define a class, Generally, a class specification has two parts:
- A class declaration, which describes the data component, in terms of data members, and the public interface, in terms of member functions, termed methods
- The class method definitions, which describe how certain class member functions are implemented
Roughly speaking, the class declaration provides a class overview, whereas the method definitions supply the details.
What is an Interface?
For classes, we speak of the public interface. In this case, the public is the program using the class, the interacting system consists of the class objects, and the interface consists of the methods provided by whoever wrote the class. The interface enables you, the programmer, to write code that interacts with class objects, and thus it enables the program to use the class objects. For example, to find the number of characters in a string object, you don't open up the object to what is inside; you just use the size() method provided by the class creators. It turns out that the class design denies direct access to the public user. But the public is allowed to use the size() method. The size() method, then, is part of the public interface between the user and a string class object.
Similarly, the getline() method is part of the istream class public interface.
If you want a more personal relationship, instead of thinking of the program using a class as the public user, you can think of the person writing the program using the class as the public user. But in any case, to use a class, you need to know its public interface; to write a class, you need to create its public interface.
The keywords private public describe access control for class members.
Any program that uses an object of a particular class can access the public portions directly. A program can access the private members of an object only by using the public member functions. Thus, the public member functions act as go-betweens between a program and an object's private members; they provide the interface between object and program.
data hiding, this isulation of data from direct access by a program is called data hiding.
A class design attempts to separate the public interface from the specifics of the implementation. The public interface represents the abstraction component of the design.
Gathering the implementation details together and separating them from the abstraction is called encapsulation. Data hiding (putting data into the private section of a class) is an instance of encapsulation, and so hiding functional details of an implementation in the private section.
Another example of encapsulation is the usual practice of placing class function definitions in a seperate file from the class declaration.
Note that data hiding not only prevents you form accessing data directly, but it also absolves you (in the roll as user of the class) from needing to know how the data is represented.
For example a class show() member can display the total value of a holding, this value can be stored as part of an object, or it can be calculated when needed.
From the standpoint of the user, it makes no difference which approach is used.
What you need to know is what the different member functions accomplish; that is, you need to know what kinds of arguments a member function takes and what kind of return value it has.
The principle is to separate the details of the implementation from the design of the interface.
If you later find a better way to implement the data representation or the details of the member functions, you can change those details without changing the program interface, and that makes programs much easier to maintain.
Implementing Class Member Functions
You still have to create the second part of the class specification: providing code for those member functions represented by a prototype in the class declaration. Member function definitions are much like regular functions. Each has a function header and a function body. Member function definitions can have return types and arguments. But they also have two special characteristics:
- When you define a member function, you use the scope-resolution operator (::) to identify the class to which the function belongs
- Class methods can access the private components of the class
First, the function header for a member function uses the scope-resolution operator (::) to indicate to which class the function belongs.
See this example:
void Stock::update(double price)
This notation means you are defining the update() function that is member of the Stock class.
Thus, the scope-resolution operator resolves the identity of the class to which a method definition applies. We say that the identifier update() has class scope. Other member functions of the Stock class can, if necessary, use the update() method without using the scope-resolution operator. That is because they belong to the same class, making update() in scope.
The second special characteristic of methods is that a method can access the private members of a class. For example, the show() method can use code like this:
cout << "Company: " << company
<< " Shares: " << shares << endl;
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << endl;
Where all those variables are in the private section of the class.
Here company, shares, and so on are private data members of the Stock class. If you try to use a nonmember function to access these data members, the compiler stops you cold in your tracks. (However, friend functions, later discussed provide an exception).
Which Object Does a Method Use?
Now we come to one of the most important aspects of using objects: how you apply a class method to an object. Code such as
shares += num;
uses the shares member of an object. But which object? That is an excellent question! To answer it, first consider how you create an object. The simplest way is to declare class variables:
Stock kate, joe;
This creates two objects of the Stock class, one named kate and one named joe.
Next, consider how to use a member function with one of these objects. The answer is, as with structures and structure members, is to use the membership operator:
kate.show(); // the kate object calls the member function
joe.show(); // the joe object calls the member function
The first call here invokes show() as a member of the kate object. This means the method interprets shares as kate.shares and share_val as kate.share_val. Similarly, the call joe.show() method interprets shares and share_val as joe.shares and joe.share_val respectively.
Each new object you create contains storage for its own internal variables, the class members. But all objects of the same class share the same set of class methods, with just one copy of each method.
Suppose, for example, that kate and joe are Stock objects. In that case, kate.shares occupies one chunk of memory and joe.shares occupies a second chunk of memory. But kate.show() and joe.show() both invoke the same method--that is, both execute the same block of code. They just apply the code to different data. Calling a member function is what some OOP languages term sending a message. Thus, sending the same message to two different objects invoke the same method but applies it to two different objects.
When the Stock class works as you want it to, you can use it as a user-defined type in other programs. The critical point in using the new type is to understand what member functions do;
You shouldn't have to think about the implementation details.
The Client/Server Model
OOP programmers often discuss program design in terms of a client/server model. In this conceptualization, the client is the program that uses the class. The class declaration, including the class methods, constitude the server, which is a resource that is available to the programs that need it. The client uses the server through the publicly defined interface only. This means that the client's only responsibility, and, by extension, the client's programmer's only responsibility, is to knwo that interface. The server's responsibility, and by extension, the server's designer's responsibility, is to see that the server reliably and accurately performs according to that interface. Any changes the server designer makes to the class design should be to details of the implementation, not to the interface. This allows programmers to improve the client and the server independently of each other, without changes in the server having unforseen repercussions on the client's behavior.
Full Qualified Name
char * Bozo::Retort()
The full, or qualified name of the above funtion is: Bozo::Retord(). The name Retort(), on the other hand, is an abbreviation of the qualified name, and it can be used only in certain circumstances, such as in the code for the class methods.
To create an object, which is a particular example of a class, you use the class name as if it where a type name:
Bozo bozetta;
This works because a class is a user-defined type.
You invoke a class member function, or method, by using a class object. You do so by using the dot membership operator:
This invokes the Retort() member function, and whenever the code for that function refers to a particular data member, the function uses the value that member has in the bozetta object.
vrijdag 29 juni 2007
static duration variables
To create a static duration variable with external linkage, you declare it outside any block.
To create a static duration variable with internal linkage, you declare it outside any block and use the static storage class modifier.
To create a static duration variable with no linkage, you declare it inside a block, using the static modifier.
See example:
...
int global = 1000; // static duration, external linkage
static int one_file = 50; // static duration, internal linkage
int main()
{
...
}
void funct1(int n)
{
static int count = 0; // static duration, no linkage
int llama = 0;
}
To create a static duration variable with internal linkage, you declare it outside any block and use the static storage class modifier.
To create a static duration variable with no linkage, you declare it inside a block, using the static modifier.
See example:
...
int global = 1000; // static duration, external linkage
static int one_file = 50; // static duration, internal linkage
int main()
{
...
}
void funct1(int n)
{
static int count = 0; // static duration, no linkage
int llama = 0;
}
donderdag 28 juni 2007
external linkage, internal linkage
A name with external linkage can be shared accross files.
A name with internal linkage can be shared by functions within a single files.
Names of automatic variables have no linkage because they are not shared.
A name with internal linkage can be shared by functions within a single files.
Names of automatic variables have no linkage because they are not shared.
woensdag 27 juni 2007
Storage Duration, Scope, and Linkage
C++ uses three separate schemes for storing data, and the schemes differ in how long they preserve data in memory:
- Automatic storage duration--Variables declared inside a function definition--including function parameters--have automatic storage duration. They are created when program execution enters the function or block in which they are defined, and the memory used for them is freed when execution leaves the function or block. C++ has two kinds of automatic storage duration variables.
- Static storage duration--Variables defined outside a function definition or else by using the keyword static have static storage duration. They persist for the entire time a program is running. C++ has three kinds of static storage duration variables.
- Dynamic storage duration--Memory allocated by the new operator persists until it is freed with the delete operator or until the program ends, whichever comes first. This memory has dynamic storage duration and somethimes is termed the free store.
Scope and Linkage
Scope describes how widely visible a name is in a file (translation unit). For example, a variable defined in a function can be used in that function, but not in another, whereas a variable defined in a file above the function definitions can be used in all the functions. Linkage describes how a name can be shared in different units. A name with external linkage can be shared accross files, and a name with internal linkage can be shared by functions within a single file.
Names of automatic variables have no linkage because they are not shared.
A C++ variable can have one of several scopes. A variable that has local scope (also termed block scope) is known only within the block in which it is defined. Recall that a block is a series of statements enclosed in braces. A function body, for example, is a block, but you can have other blocks nested within the function body. A variable that has global scope (also termed file scope) is known throughout the file after the point where it is defined. Automatic variables have a local scope, and a static variable can have either scope, depending on how it is defined.
Names used in a function prototype scope are known just within the parentheses enclosing the argument list. Members declared in a class have class scope (see later blogs), Variables declared in a namespace have namespace scope. (Now that namespaces have been added to the C++ language, the global scope has become a special case of namespace scope.)
C++ functions can have class scope or namespace scope, including global scope, but they can't have local scope. (Because a function can't be defined inside a block, if a function were to have local scope, it could only be known to itself, and hence couldn't be called by another function. Such a function couldn't function.) I guess you also should know a function can not be defined in a function, a function cannot be nested in a function.
The various C++ storage choiches are characterized by their storage duration, their scope, and their linkage.
If you like to read more about this, buy a book on it like: C++ primer plus by Stephen Prata, that is where most of my blogs are based on.
- Automatic storage duration--Variables declared inside a function definition--including function parameters--have automatic storage duration. They are created when program execution enters the function or block in which they are defined, and the memory used for them is freed when execution leaves the function or block. C++ has two kinds of automatic storage duration variables.
- Static storage duration--Variables defined outside a function definition or else by using the keyword static have static storage duration. They persist for the entire time a program is running. C++ has three kinds of static storage duration variables.
- Dynamic storage duration--Memory allocated by the new operator persists until it is freed with the delete operator or until the program ends, whichever comes first. This memory has dynamic storage duration and somethimes is termed the free store.
Scope and Linkage
Scope describes how widely visible a name is in a file (translation unit). For example, a variable defined in a function can be used in that function, but not in another, whereas a variable defined in a file above the function definitions can be used in all the functions. Linkage describes how a name can be shared in different units. A name with external linkage can be shared accross files, and a name with internal linkage can be shared by functions within a single file.
Names of automatic variables have no linkage because they are not shared.
A C++ variable can have one of several scopes. A variable that has local scope (also termed block scope) is known only within the block in which it is defined. Recall that a block is a series of statements enclosed in braces. A function body, for example, is a block, but you can have other blocks nested within the function body. A variable that has global scope (also termed file scope) is known throughout the file after the point where it is defined. Automatic variables have a local scope, and a static variable can have either scope, depending on how it is defined.
Names used in a function prototype scope are known just within the parentheses enclosing the argument list. Members declared in a class have class scope (see later blogs), Variables declared in a namespace have namespace scope. (Now that namespaces have been added to the C++ language, the global scope has become a special case of namespace scope.)
C++ functions can have class scope or namespace scope, including global scope, but they can't have local scope. (Because a function can't be defined inside a block, if a function were to have local scope, it could only be known to itself, and hence couldn't be called by another function. Such a function couldn't function.) I guess you also should know a function can not be defined in a function, a function cannot be nested in a function.
The various C++ storage choiches are characterized by their storage duration, their scope, and their linkage.
If you like to read more about this, buy a book on it like: C++ primer plus by Stephen Prata, that is where most of my blogs are based on.
Seperate Compilation
To seperate compile files, you have to split your source file into several files.
This is an example what to put in a header file:
- Function prototypes
- Symbolic constants defined using #define or const
- Structure declarations
- Class declarations
- Template declarations
- Inline functions
Data declared const and inline functions have special linkage properties (described shortly) that allow them to be placed in header files without causing problems.
For include files, when you created them yourself, in the source where you use them, use "includefile.h" instead of because if the include file is in angle brackets, because the C++ compiler then looks in the hosts system files directory, that holds the standard header files. But if the header file is enclosed in double quotations marks, the compiler first looks in the current working directory or the sourcecode directory.
So you should use double quotations marks if you want to use your own header files/ include files.
You should include a header file just once in a file. That might seem to be an easy thing to remember, but it's possible yo include a header file several times without knowing you did so.
For example you might use a header file that includes another header file. There's a standard C/C++ technique for avoiding multiple inclusions of header files. It's based on the preprocessor #ifndef (for if not defined) directive. A code segment like
#ifndef COORDIN_H_
...
#endif
Means process the statements between the #ifndef and #endif only if the name COORDIN_H_ has not been defined previously by the preprocessor #define directive.
By the way, although we've discussed separate compilation in terms of files, the C++ Standard use the term translation unit instead of file in order to preserve greater generality; the file metaphore is not the only possible way to organize information for a computer.
Multiple Library linking
The C++ Standard allows each compiler designer the latitude to implement name decoration or mangling as it sees fit. So you should be aware that binary modules (object-code files) created with different compilers will, most likely, not linked properly. That is, the two compilers will generate different decorated names for the same function. This name difference will prevent the linker from matching the function call generated by one compiler with the function definition generated by a second compiler. When attempting to link compiled modules, you should make sure that each object file or library was generated with the same compiler. If you are provided with the source code, you can usually resolve link errors by recompiling the source with your compiler.
This is an example what to put in a header file:
- Function prototypes
- Symbolic constants defined using #define or const
- Structure declarations
- Class declarations
- Template declarations
- Inline functions
Data declared const and inline functions have special linkage properties (described shortly) that allow them to be placed in header files without causing problems.
For include files, when you created them yourself, in the source where you use them, use "includefile.h" instead of
So you should use double quotations marks if you want to use your own header files/ include files.
You should include a header file just once in a file. That might seem to be an easy thing to remember, but it's possible yo include a header file several times without knowing you did so.
For example you might use a header file that includes another header file. There's a standard C/C++ technique for avoiding multiple inclusions of header files. It's based on the preprocessor #ifndef (for if not defined) directive. A code segment like
#ifndef COORDIN_H_
...
#endif
Means process the statements between the #ifndef and #endif only if the name COORDIN_H_ has not been defined previously by the preprocessor #define directive.
By the way, although we've discussed separate compilation in terms of files, the C++ Standard use the term translation unit instead of file in order to preserve greater generality; the file metaphore is not the only possible way to organize information for a computer.
Multiple Library linking
The C++ Standard allows each compiler designer the latitude to implement name decoration or mangling as it sees fit. So you should be aware that binary modules (object-code files) created with different compilers will, most likely, not linked properly. That is, the two compilers will generate different decorated names for the same function. This name difference will prevent the linker from matching the function call generated by one compiler with the function definition generated by a second compiler. When attempting to link compiled modules, you should make sure that each object file or library was generated with the same compiler. If you are provided with the source code, you can usually resolve link errors by recompiling the source with your compiler.
dinsdag 26 juni 2007
Explicit Specializations (Templates)
Suppose you define a structure like the following:
struct job
{
char name[40];
double salary;
int floor;
};
Also, suppose you want to be able to swap the contents of the two structures. The original template, the one before this blog, uses the following code to effect a swap:
temp = a;
a = b;
b = temp;
Because C++ allows you to assign one structure to another, this works fine, even if type Any is a
job structure. But suppose you want only to swap the salary and floor members, keeping the name members unchanged. This requires different code, but the arguments to Swap() would be the same as for the first case (references to two job structures), so you can't use template overloading to supply alternative code.
However, you can supply a specialized function definition, called an explicit specialization, with the required code, If the compiler finds a specialized definition that exactly matches a function call, it uses that definition without looking for templates.
The specialization mechanism has changed with the evolution of C++. We'll look at the current form as mandated by the C++ Standard.
- For a given function name, you can have a non-template function, a template function, and an explicit specialization template function, along with overloaded versions of all of these.
- The prototype and definition for an explicit specialization should be preceded by template <> and should mention the specialized type by name.
- A specialization overrides the regular template, and a non-template function overides both.
Here's how prototypes for swapping type job structures would look for these three forms:
// non-template function prototype
void Swap(job &, job &);
// template prototype
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap(job &, job &);
As mentioned previously, if more than one of these prototypes is present, the compiler chooses the non-template version over explicit specializations and template versions, and it chooses an explicit specialization over a version generated from a template. For example, in the following code, the first call to Swap() uses the general template, and the second call uses the explicit specialization, based on the job type:
...
template // template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap(job &, job &);
int main()
{
double u, v;
...
Swap(u, v); // use template
job a, b;
...
Swap(a, b); // use void Swap(job &, job &)
}
The in Swap is optional because the function argument types indicate that this is a specialization for job. Thus the prototype can also be written this way:
template <> void Swap(job &, job &); // simpler form
struct job
{
char name[40];
double salary;
int floor;
};
Also, suppose you want to be able to swap the contents of the two structures. The original template, the one before this blog, uses the following code to effect a swap:
temp = a;
a = b;
b = temp;
Because C++ allows you to assign one structure to another, this works fine, even if type Any is a
job structure. But suppose you want only to swap the salary and floor members, keeping the name members unchanged. This requires different code, but the arguments to Swap() would be the same as for the first case (references to two job structures), so you can't use template overloading to supply alternative code.
However, you can supply a specialized function definition, called an explicit specialization, with the required code, If the compiler finds a specialized definition that exactly matches a function call, it uses that definition without looking for templates.
The specialization mechanism has changed with the evolution of C++. We'll look at the current form as mandated by the C++ Standard.
- For a given function name, you can have a non-template function, a template function, and an explicit specialization template function, along with overloaded versions of all of these.
- The prototype and definition for an explicit specialization should be preceded by template <> and should mention the specialized type by name.
- A specialization overrides the regular template, and a non-template function overides both.
Here's how prototypes for swapping type job structures would look for these three forms:
// non-template function prototype
void Swap(job &, job &);
// template prototype
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap
As mentioned previously, if more than one of these prototypes is present, the compiler chooses the non-template version over explicit specializations and template versions, and it chooses an explicit specialization over a version generated from a template. For example, in the following code, the first call to Swap() uses the general template, and the second call uses the explicit specialization, based on the job type:
...
template
void Swap(Any &, Any &);
// explicit specialization for the job type
template <> void Swap
int main()
{
double u, v;
...
Swap(u, v); // use template
job a, b;
...
Swap(a, b); // use void Swap
}
The
template <> void Swap(job &, job &); // simpler form
Function Templates
A function template is a generic function description; that is, it defines a function in terms of a generic type for which a specific type, such as int or double, can be substituted.
By passing a type as parameter to a template, you cause the compiler to generate a function for that particular type. Because templates let you program in terms of a generic type instead of a specific type, the process is somethimes called generic programming.
Because types are represented by parameters, the template feature is somethimes referred as parameterized types.
Function templates enable you to define a function in terms of some arbitrary type. For example, you can set up a swapping template like this:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The first line specifies that you are setting up a template and you're naming the arbitrary type Any. The keyword template and class are obligatory, except you can use the keyword typename instread of class. Also, you must use the angle brackets. The type name (Any, in this example) is your choice, as long as you follow the usual C++ naming rules; many programmers use simple names such as T. The rest of the code describes the algorithm for swapping two values of type Any. The template does not create any functions. Instead, it provides the compiler with directions about how to define a function. If you want a function to swap ints, then the compiler creates a function following the template pattern, substituting int for Any. Similarly, if you need a function to swap doubles, the compiler follows the template, substituting the double type for Any.
The keyword typename is a recent addition to C++. You can use it instead of the keyword class in this particular context. That is, you can write the template definition this way:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The typename keyword makes it a bit more obvious that the parameter Any represents a type;
however, large libraries of code have already been developed by using the older keyword class. The C++ standard treats the two keywords identically when they are used in this context.
To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function.
In a program, the template could be used as follows:
template // or typename Any
void Swap(Any &a, Any &b);
then after main(){}
// function template definition
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
Note that function templates don't make executable programs any shorter!
The final code does not contain templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.
By passing a type as parameter to a template, you cause the compiler to generate a function for that particular type. Because templates let you program in terms of a generic type instead of a specific type, the process is somethimes called generic programming.
Because types are represented by parameters, the template feature is somethimes referred as parameterized types.
Function templates enable you to define a function in terms of some arbitrary type. For example, you can set up a swapping template like this:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The first line specifies that you are setting up a template and you're naming the arbitrary type Any. The keyword template and class are obligatory, except you can use the keyword typename instread of class. Also, you must use the angle brackets. The type name (Any, in this example) is your choice, as long as you follow the usual C++ naming rules; many programmers use simple names such as T. The rest of the code describes the algorithm for swapping two values of type Any. The template does not create any functions. Instead, it provides the compiler with directions about how to define a function. If you want a function to swap ints, then the compiler creates a function following the template pattern, substituting int for Any. Similarly, if you need a function to swap doubles, the compiler follows the template, substituting the double type for Any.
The keyword typename is a recent addition to C++. You can use it instead of the keyword class in this particular context. That is, you can write the template definition this way:
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
The typename keyword makes it a bit more obvious that the parameter Any represents a type;
however, large libraries of code have already been developed by using the older keyword class. The C++ standard treats the two keywords identically when they are used in this context.
To let the compiler know that you need a particular form of swap function, you just use a function called Swap() in your program. The compiler checks the argument types you use and then generates the corresponding function.
In a program, the template could be used as follows:
template
void Swap(Any &a, Any &b);
then after main(){}
// function template definition
template
void Swap(Any &a, Any &b)
{
Any temp;
temp = a;
a = b;
b = temp;
}
Note that function templates don't make executable programs any shorter!
The final code does not contain templates; it just contains the actual functions generated for the program. The benefits of templates are that they make generating multiple function definitions simpler and more reliable.
Function Overloading
Function polymorphism is a neat C++ addition to C's capabilities. function polymorphism, also called function overloading, lets you use multiple functions sharing the same name.
polymorphism means having many forms.
So function polymorphism lets a function have many forms.
Similarly, the expression function overloading means you can attach more than one function to the same name, thus overloading the name.
You can use function overloading to design a family of functions that do essentially the same thing, but using different argument lists.
Overloaded functions are analogous to verbs having more than one meaning.
The key to function overloading it a function's argument list, also called the function signature.
If two functions use the same number and types of arguments in the same order, they have the same signature. the variable names don't matter.
C++ enables you to define two functions by the same name, provided that the functions have different signatures. The signature can differ in the number of arguments or in the type of arguments, or both. For example you can define a set of print() functions with the following prototypes:
void print(const char * str, int width); // #1
void print(double d, int width); // #2
void print(long l, int width); // #3
void print(int i, int width); // #4
void print(const char * str); // #5
When you use a print() function, the compiler matches your use to the prototype that has the same signature:
print("Pancakes", 15); // use #1
print("Syrup"); // use #5
print(1999.0, 10); // use #2
print(1999, 12); // use #4
print(1999L, 15); // use #3
When to use function overloading?
You might find function overloading fascinating, but you shouldn't overuse it. You should reserve function overloading for functions that perform basically the same task, but with different forms of data. Also you might want to check wether you can accomplish the same end by using default arguments.
char * left(const char * str, unsigned n); // two arguments
char * left(const char * str); // one argument
But using a single function with a default argument is simpler. There's just one function to write, instead of two, and the program requires memory for just one function, instead of two.
If you decide to modify the function, you have to edit only one. However, if you require different types of arguments, default arguments are of no avail, so in that case, you should use function overloading.
How does C++ keep track of which overloaded function is which?
It assigns a secret identity to each of these functions.
When you compile programs, the C++ compiler performs a bit of magic on your behalf--known as name decoration or name mangling--through which each function name is encrypted, based on the formal parameter types specified in the function's prototype. Consider the following undecorated function prototype:
long MyFunctionFoo(int, float);
For its own use, the compiler documents this interface by transforming the name into an internal representation with a more unsightly appearance, perhaps something like this:
?myFunctionFoo@@YAXH@Z
The apperent gibberish decorating the original name(or mangling is, depending on your attitude)
encodes the number and types of parameters. A different function signature would result in a different set of symbols being added, and different compilers would use different conventions for their efforts at decorating.
polymorphism means having many forms.
So function polymorphism lets a function have many forms.
Similarly, the expression function overloading means you can attach more than one function to the same name, thus overloading the name.
You can use function overloading to design a family of functions that do essentially the same thing, but using different argument lists.
Overloaded functions are analogous to verbs having more than one meaning.
The key to function overloading it a function's argument list, also called the function signature.
If two functions use the same number and types of arguments in the same order, they have the same signature. the variable names don't matter.
C++ enables you to define two functions by the same name, provided that the functions have different signatures. The signature can differ in the number of arguments or in the type of arguments, or both. For example you can define a set of print() functions with the following prototypes:
void print(const char * str, int width); // #1
void print(double d, int width); // #2
void print(long l, int width); // #3
void print(int i, int width); // #4
void print(const char * str); // #5
When you use a print() function, the compiler matches your use to the prototype that has the same signature:
print("Pancakes", 15); // use #1
print("Syrup"); // use #5
print(1999.0, 10); // use #2
print(1999, 12); // use #4
print(1999L, 15); // use #3
When to use function overloading?
You might find function overloading fascinating, but you shouldn't overuse it. You should reserve function overloading for functions that perform basically the same task, but with different forms of data. Also you might want to check wether you can accomplish the same end by using default arguments.
char * left(const char * str, unsigned n); // two arguments
char * left(const char * str); // one argument
But using a single function with a default argument is simpler. There's just one function to write, instead of two, and the program requires memory for just one function, instead of two.
If you decide to modify the function, you have to edit only one. However, if you require different types of arguments, default arguments are of no avail, so in that case, you should use function overloading.
How does C++ keep track of which overloaded function is which?
It assigns a secret identity to each of these functions.
When you compile programs, the C++ compiler performs a bit of magic on your behalf--known as name decoration or name mangling--through which each function name is encrypted, based on the formal parameter types specified in the function's prototype. Consider the following undecorated function prototype:
long MyFunctionFoo(int, float);
For its own use, the compiler documents this interface by transforming the name into an internal representation with a more unsightly appearance, perhaps something like this:
?myFunctionFoo@@YAXH@Z
The apperent gibberish decorating the original name(or mangling is, depending on your attitude)
encodes the number and types of parameters. A different function signature would result in a different set of symbols being added, and different compilers would use different conventions for their efforts at decorating.
When to use Reference Arguments
There are two main reasons for using reference arguments:
- To allow you to alter a data object in the calling function
- To speed up a program by passing a reference instead of an entire object
The second is most imporatant for larger data objects, such as structures and class objects.
These two reasons are the same reasons you might have for using a pointer argument.
This makes sense because reference arguments are really just a different initerface for pointer-based code. So when should you use a reference? use a pointer? pass by value? The following are some guidelines.
A function used passed data without modifying it:
- If the data object is small, such as a build-in data type or a small structure, pass it by value.
- If the data object is an array, use pointer because that is your only choice, Make the pointer a pointer to const.
- If the data is a good-sized structure, use a const pointer or a const reference to increase program effficiency. You save time and space needed to copy a structure or a class design. Make the pointer or reference const.
- If the data object is a class object, use a const reference. The semantics of class design often require using a reference, which is the main reason C++ added this feature. Thus, the standard way to pass class object arguments is by reference.
A function modifies data in the calling function:
- If the data object is a built-in data type, use a pointer. If you spot code like fixit(&x), where x is an int, it's pretty clear that this function intents to modify x.
- If the data object is an array, use your only choice: a pointer
- If the data object is a structure, use a reference or a pointer
- If the data object is a class object, use a reference.
Of course, these are just guidelines, and there might be reasons for making different choices.
For example, cin uses references for basic types so that you can use cin >> n instead of cin >> &n.
- To allow you to alter a data object in the calling function
- To speed up a program by passing a reference instead of an entire object
The second is most imporatant for larger data objects, such as structures and class objects.
These two reasons are the same reasons you might have for using a pointer argument.
This makes sense because reference arguments are really just a different initerface for pointer-based code. So when should you use a reference? use a pointer? pass by value? The following are some guidelines.
A function used passed data without modifying it:
- If the data object is small, such as a build-in data type or a small structure, pass it by value.
- If the data object is an array, use pointer because that is your only choice, Make the pointer a pointer to const.
- If the data is a good-sized structure, use a const pointer or a const reference to increase program effficiency. You save time and space needed to copy a structure or a class design. Make the pointer or reference const.
- If the data object is a class object, use a const reference. The semantics of class design often require using a reference, which is the main reason C++ added this feature. Thus, the standard way to pass class object arguments is by reference.
A function modifies data in the calling function:
- If the data object is a built-in data type, use a pointer. If you spot code like fixit(&x), where x is an int, it's pretty clear that this function intents to modify x.
- If the data object is an array, use your only choice: a pointer
- If the data object is a structure, use a reference or a pointer
- If the data object is a class object, use a reference.
Of course, these are just guidelines, and there might be reasons for making different choices.
For example, cin uses references for basic types so that you can use cin >> n instead of cin >> &n.
maandag 25 juni 2007
Objects, Inheritance, and References
The ostream and ofstream classes bring an interesting property of references to the fore.
As you may remember from other things I blogged, objects of the ofstream type can use ostream methods, allowing file input/output to use the same forms as console input/output.
The language feature that makes it possible to pass features from one class to another is called inheritance.
In brief, ostream is termed a base class (because the ofstream class is based on it) and ofstream is termed a derived class(becuase it is derived from ostream). A derived class inherits the base class methods, which means that an ofstream object can use base class features such as the precision() and setf() formatting methods.
Another aspect if inheritance is that a base class reference can refer to a derived class object without requiring a type cast. The practical upshot of this is that you can define a function having a base class reference parameter, and that function can be used with base class objects and also with derived objects. For example, a function with a type ostream & parameter can accept an ostream object, such as cout, or an ofstream object such as you might declare equally well.
As you may remember from other things I blogged, objects of the ofstream type can use ostream methods, allowing file input/output to use the same forms as console input/output.
The language feature that makes it possible to pass features from one class to another is called inheritance.
In brief, ostream is termed a base class (because the ofstream class is based on it) and ofstream is termed a derived class(becuase it is derived from ostream). A derived class inherits the base class methods, which means that an ofstream object can use base class features such as the precision() and setf() formatting methods.
Another aspect if inheritance is that a base class reference can refer to a derived class object without requiring a type cast. The practical upshot of this is that you can define a function having a base class reference parameter, and that function can be used with base class objects and also with derived objects. For example, a function with a type ostream & parameter can accept an ostream object, such as cout, or an ofstream object such as you might declare equally well.
passing a C-Style String to a string object parmeter
string version1(const string & s1, const string & s2)
{
string temp;
temp = s2 + s1 + s2;
return temp;
}
string input;
getline(cin, input);
result = version1(input, "***");
Now the question is, how can it be that the string literal "***" can be passed as it is a string object to the function version1?
The answer has two parts:
1. The string class defines a char * to string conversion.
2. If a actual argument does not match the const reference argument, and the argument can be converted to the correct type, then a temporary variable of the correct type is created, a string in this case, and is used during the existence of the function called.
Earlier you saw that a const double & parameter can handle an int argument in this fashion.
The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char.
Hence, the following works fine:
result = version1(input, "***");
{
string temp;
temp = s2 + s1 + s2;
return temp;
}
string input;
getline(cin, input);
result = version1(input, "***");
Now the question is, how can it be that the string literal "***" can be passed as it is a string object to the function version1?
The answer has two parts:
1. The string class defines a char * to string conversion.
2. If a actual argument does not match the const reference argument, and the argument can be converted to the correct type, then a temporary variable of the correct type is created, a string in this case, and is used during the existence of the function called.
Earlier you saw that a const double & parameter can handle an int argument in this fashion.
The convenient outcome of this is that if the formal parameter is type const string &, the actual argument used in the function call can be a string object or a C-style string, such as a quoted string literal, a null-terminated array of char, or a pointer variable that points to a char.
Hence, the following works fine:
result = version1(input, "***");
why use const with reference return
You might be wondering why a lot of functions you see return a const reference.
Here is an example:
use(looper).used = 10;
Here looper is a structure, and the function use() returns a non-const reference to the structure, as you see this makes it possible to write obscure code, by which you directly modify the returned structure. If the use() function had returned a const reference, then such code was not possible. You might say it is cool to return a non-const reference, because the code can be short, but the book I read says it is obscure to code like this. Think for yourself when creating code.
Another example:
sysop newgal = {"Polly Morf", "Polly's not a hacker.", 0};
use(looper) = newgal;
now looper is a copy from newgal, this kind of code is not what you like.
In short, by omitting const, you can write shorter but more obscure-looking code.
Occasionally omitting const does make sense. The overloaded << operator later discussed is an example.
Here is an example:
use(looper).used = 10;
Here looper is a structure, and the function use() returns a non-const reference to the structure, as you see this makes it possible to write obscure code, by which you directly modify the returned structure. If the use() function had returned a const reference, then such code was not possible. You might say it is cool to return a non-const reference, because the code can be short, but the book I read says it is obscure to code like this. Think for yourself when creating code.
Another example:
sysop newgal = {"Polly Morf", "Polly's not a hacker.", 0};
use(looper) = newgal;
now looper is a copy from newgal, this kind of code is not what you like.
In short, by omitting const, you can write shorter but more obscure-looking code.
Occasionally omitting const does make sense. The overloaded << operator later discussed is an example.
Being carefull what a return reference refers to!
The single most important point to remember when returning a reference is avoid returning a reference to a memory location that ceases to exist when the function terminates!
What you want to avoid is code along these lines:
const sysop & clone2(sysop & sysopref)
{
sysop newguy; // first step to big error
newguy = sysopref; // copy info
return newguy; // return reference to copy
}
This has the unfortunate effect of returning a reference to a temporary variable (newguy) that passes from existence as soon as the function terminates.
Similarly you should avoid returning pointers to such temporary variables.
The simplest way to avoid this problem is to return a reference that was passed as an argument to the function. A reference parameter will refer to data used by the calling function, hence the returned reference will refer to that same data.
A second method is to use new to create new storage.
const sysop & clone(sysop & sysopref)
{
sysop * psysop = new sysop;
*psysop = sysopref; // copy info
return *psysop;
}
The first statement creates a nameless sysop structure. The pointer psysop points to the structure, so *psysop is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure. You could then use the function this way:
sysop & jolly = clone(looper);
This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() hides the call to new, making it simpler to forget to use delete later. The auto_ptr template discussed later can help automate the deletion process.
What you want to avoid is code along these lines:
const sysop & clone2(sysop & sysopref)
{
sysop newguy; // first step to big error
newguy = sysopref; // copy info
return newguy; // return reference to copy
}
This has the unfortunate effect of returning a reference to a temporary variable (newguy) that passes from existence as soon as the function terminates.
Similarly you should avoid returning pointers to such temporary variables.
The simplest way to avoid this problem is to return a reference that was passed as an argument to the function. A reference parameter will refer to data used by the calling function, hence the returned reference will refer to that same data.
A second method is to use new to create new storage.
const sysop & clone(sysop & sysopref)
{
sysop * psysop = new sysop;
*psysop = sysopref; // copy info
return *psysop;
}
The first statement creates a nameless sysop structure. The pointer psysop points to the structure, so *psysop is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure. You could then use the function this way:
sysop & jolly = clone(looper);
This makes jolly a reference to the new structure. There is a problem with this approach: You should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() hides the call to new, making it simpler to forget to use delete later. The auto_ptr template discussed later can help automate the deletion process.
Reference arguments, use const when you can!
There are three strong reasons to declare reference arguments as references to constant data:
- Using const protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype only can accept non-const data.
- Using a const reference allows the function to generate and use a temporary variable appropriately.
You should declare formal reference arguments as const whenever it's appropriate to do so.
- Using const protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype only can accept non-const data.
- Using a const reference allows the function to generate and use a temporary variable appropriately.
You should declare formal reference arguments as const whenever it's appropriate to do so.
References as Function Parameters
Most often references are used as function parameters, making a variable name in a function an alias for a variable in the calling program.
This method of passing arguments is called: Passing by reference!
Passing by reference allows a called function to access variables in the calling function.
C++'s addition of the feature is break down from C, which only passes by value.
Passing by value, recall, results in the called function working with copies of values from the calling program/function.'Of course, C lets you get arround the passing by value limitation by using pointers.
Using passing by value, if a function has one argument, makes two variables, one the argument and one variable in the function initialized with the value of the argument.
Using passing by reference, if a function has one argument, makes one variable, the argument, and a reference in the function to that variable, which is two names for one variable.
Functions that pass by value, can use many kinds of actual arguments:
double cube(double a)
{
a *= a * a;
return a;
}
double z = cube(x + 2.0); // evaluate x + 2.0, pass value
z = cube(8.0); // pass the value 8.0
int k = 10;
z = cube(k); // convert value of k to double, pass value
double yo[3] = { 2.2, 3.3, 4.4};
z = cube(yo[2]); // pass the value 4.4
Suppose you try similar arguments for a function with a reference parameter:
double refcube(double & ra)
{
ra *= ra * ra;
return ra;
}
It would seem that passing a reference should be more restrictive. After all, if ra is the alternative name for a variable, then the actual arguments should be that variable. Something like:
double z = refcube(x + 3.0); // may not compile
doesn't appear to make sense because the expression x + 3.0 is not a variable. For example you can't assign a value to such expression:
x + 3.0 = 5.0 // nonsensical
In some cases, the compiler will accept x + 3.0.
What happens is that because x + 3.0 is not a type double variable, the program creates a temporary, nameless variable, intializing it to the value of the expression x + 3.0. Then ra becomes a reference to that temporary variable. Let's take a closer look at temporary variables and see when they are and are not created.
C++ can generate a temporary variable if the actual argument doesn't match a reference argument. Currently C++ permits this only if the argument is a const reference, but this is a new restriction.
Provided that the reference parameter is a const, the compiler generates a temporary variable in two kinds of situations:
- When the actual argument is the correct type but isn't a lvalue
- When the actual argument is of the wrong type, but it's of a type that can be converted to the correct type
An argument that is an lvalue is a data object that can be referenced. For example, a variable, an array element, a structure member, a reference, and a dereferenced pointer are lvalues.
Non-lvalues include literal constants and expressions with multiple terms. For example, supose you redifine refcube() so that it has a constant reference argument:
double refcube(const double &ra)
{
return ra * ra * ra;
}
Now consider the following code:
double side = 3.0;
double * pd = &side;
double & rd = side;
long edge = 5L;
double lens[4] = { 2.0, 5.0, 10.0, 12.0};
double c1 = refcube(side); // ra is side
double c2 = refcube(lens[2]); // ra is lens[2]
double c3 = refcube(rd); // ra is rd is side
double c4 = refcube(*pd); // ra is *pd is side
double c5 = refcube(edge); // ra is temporary variable
double c6 = refcube(7.0); // ra is temporary variable
double c7 = refcube(side + 10.0); // ra is temporary variable
The arguments side, lens[2], rd and *pd are type double data objects with names, so it is possible to generate a reference for them, and no temporary variables are needed. (Recall that an element of an array behaves like a variable of the same type as the element.)
But although edge is a variable, it is of the wrong type. A reference to a double can't refer to a long. The arguments 7.0 and side + 10.0, on the otherhand, are the right type, but they are not named data objects. In each of these cases, the compiler generates a temporary, anonymous variable and makes ra refer to it. These temporary variables last for the duration of the function call, but then the compiler is free to dump them.
So why is this behaviour okay for constant references but not otherwise?
void swapr(int & a, int & b) // use references
{
int temp;
temp = a; // use a, b for values of variables
a = b;
b = temp;
}
What would happen if you did the following under the freer rules of early C++?
long a = 3, b = 5;
swapr(a, b);
Here there is a type mismatch, so the compiler would create two temporary int variables, initialize them to 3 and 5, and then swap the contents of the temporary variables, leaving a and b unaltered,
The solution is to prohibit creating temporary variables in these situations, and that is what the C++ standard now does!
Now think about the refcube() function. Its intent is merely to use passed values, not to modify them, so temporary variables cause no harm and make the function more general in the sort of arguments is can handle. Therefor, if the declaration states that a reference is const, C++ generates temporary variables when necessary. In essence, a C++ function with a const reference formal argument and a nonmatching actual argument mimics the traditional passing by value behavior, guaranteeing that the original data is unaltered and using a temporary variable to hold the value.
REMEMBER:
If a function call argument isn't an lvalue or does not match the type of the corresponding const reference parameter, C++ creates an anonymous variable of the correct type, assigns the value of the function call argument to the anonymous variable, and has the parameter refer to that variable.
This method of passing arguments is called: Passing by reference!
Passing by reference allows a called function to access variables in the calling function.
C++'s addition of the feature is break down from C, which only passes by value.
Passing by value, recall, results in the called function working with copies of values from the calling program/function.'Of course, C lets you get arround the passing by value limitation by using pointers.
Using passing by value, if a function has one argument, makes two variables, one the argument and one variable in the function initialized with the value of the argument.
Using passing by reference, if a function has one argument, makes one variable, the argument, and a reference in the function to that variable, which is two names for one variable.
Functions that pass by value, can use many kinds of actual arguments:
double cube(double a)
{
a *= a * a;
return a;
}
double z = cube(x + 2.0); // evaluate x + 2.0, pass value
z = cube(8.0); // pass the value 8.0
int k = 10;
z = cube(k); // convert value of k to double, pass value
double yo[3] = { 2.2, 3.3, 4.4};
z = cube(yo[2]); // pass the value 4.4
Suppose you try similar arguments for a function with a reference parameter:
double refcube(double & ra)
{
ra *= ra * ra;
return ra;
}
It would seem that passing a reference should be more restrictive. After all, if ra is the alternative name for a variable, then the actual arguments should be that variable. Something like:
double z = refcube(x + 3.0); // may not compile
doesn't appear to make sense because the expression x + 3.0 is not a variable. For example you can't assign a value to such expression:
x + 3.0 = 5.0 // nonsensical
In some cases, the compiler will accept x + 3.0.
What happens is that because x + 3.0 is not a type double variable, the program creates a temporary, nameless variable, intializing it to the value of the expression x + 3.0. Then ra becomes a reference to that temporary variable. Let's take a closer look at temporary variables and see when they are and are not created.
C++ can generate a temporary variable if the actual argument doesn't match a reference argument. Currently C++ permits this only if the argument is a const reference, but this is a new restriction.
Provided that the reference parameter is a const, the compiler generates a temporary variable in two kinds of situations:
- When the actual argument is the correct type but isn't a lvalue
- When the actual argument is of the wrong type, but it's of a type that can be converted to the correct type
An argument that is an lvalue is a data object that can be referenced. For example, a variable, an array element, a structure member, a reference, and a dereferenced pointer are lvalues.
Non-lvalues include literal constants and expressions with multiple terms. For example, supose you redifine refcube() so that it has a constant reference argument:
double refcube(const double &ra)
{
return ra * ra * ra;
}
Now consider the following code:
double side = 3.0;
double * pd = &side;
double & rd = side;
long edge = 5L;
double lens[4] = { 2.0, 5.0, 10.0, 12.0};
double c1 = refcube(side); // ra is side
double c2 = refcube(lens[2]); // ra is lens[2]
double c3 = refcube(rd); // ra is rd is side
double c4 = refcube(*pd); // ra is *pd is side
double c5 = refcube(edge); // ra is temporary variable
double c6 = refcube(7.0); // ra is temporary variable
double c7 = refcube(side + 10.0); // ra is temporary variable
The arguments side, lens[2], rd and *pd are type double data objects with names, so it is possible to generate a reference for them, and no temporary variables are needed. (Recall that an element of an array behaves like a variable of the same type as the element.)
But although edge is a variable, it is of the wrong type. A reference to a double can't refer to a long. The arguments 7.0 and side + 10.0, on the otherhand, are the right type, but they are not named data objects. In each of these cases, the compiler generates a temporary, anonymous variable and makes ra refer to it. These temporary variables last for the duration of the function call, but then the compiler is free to dump them.
So why is this behaviour okay for constant references but not otherwise?
void swapr(int & a, int & b) // use references
{
int temp;
temp = a; // use a, b for values of variables
a = b;
b = temp;
}
What would happen if you did the following under the freer rules of early C++?
long a = 3, b = 5;
swapr(a, b);
Here there is a type mismatch, so the compiler would create two temporary int variables, initialize them to 3 and 5, and then swap the contents of the temporary variables, leaving a and b unaltered,
The solution is to prohibit creating temporary variables in these situations, and that is what the C++ standard now does!
Now think about the refcube() function. Its intent is merely to use passed values, not to modify them, so temporary variables cause no harm and make the function more general in the sort of arguments is can handle. Therefor, if the declaration states that a reference is const, C++ generates temporary variables when necessary. In essence, a C++ function with a const reference formal argument and a nonmatching actual argument mimics the traditional passing by value behavior, guaranteeing that the original data is unaltered and using a temporary variable to hold the value.
REMEMBER:
If a function call argument isn't an lvalue or does not match the type of the corresponding const reference parameter, C++ creates an anonymous variable of the correct type, assigns the value of the function call argument to the anonymous variable, and has the parameter refer to that variable.
zondag 24 juni 2007
Reference Variables
A reference is a name that acts as an alias, or an alternative name, for a previously defined variable. Main use for a reference variable is as a formal argument to a function.
If you use a reference as argument, the function works with the ORIGINAL data instead of with a copy. References provide a convinient alternative to pointers for processing large structures with a function, and they are essential for designing classes.
You might recall that C and C++ use the & symbol to indicate the address of a variable. C++ assigns an additional meaning to the & symbol and presses it into service for declaring references.
For example, to make rodents an alternative name for the variable rats, you could do the following:
int rats;
int & rodents = rats; // makes rodents an alias for rats
In this context, & is not the address operator. Instead, it serves as part of the type identifier.
Just as char * in a declaration means pointer-to-char, int & means reference-to-int.
The reference declaration allows you to use rats and rodents interchangeably;
both refer to the same value and the same memory location.
Note that the & in int & rodents = rats; is not the address operator, but makes rodents of type int &, that is a reference to an int variable!
cout << ", rodents address = " << &rodents << endl;
Now in the example above & is used as address operator!
It is necessary to initialize the reference when you declare it; you can't declare the reference and then assign it a value later the way you can with a pointer.
int rat;
int & rodent;
rodent = rat; // No, you can't do this.!
rodent = rats;
Does not mean to make rodent a reference to rats, but copies the value of rats to rodent, also changing rat to that value.
In short, you can set a reference by an initializing declaration, not by assignment!
Suppose you tried the following:
int rats = 101;
int * pt = &rats;
int & rodents = *pt;
int bunnies = 50;
pt = &bunnies;
Initializing rodents to *pt makes rodents refer to rats. Subsequentely altering pt to point to bunnies does not alter the fact that rodents refers to rats.
If you use a reference as argument, the function works with the ORIGINAL data instead of with a copy. References provide a convinient alternative to pointers for processing large structures with a function, and they are essential for designing classes.
You might recall that C and C++ use the & symbol to indicate the address of a variable. C++ assigns an additional meaning to the & symbol and presses it into service for declaring references.
For example, to make rodents an alternative name for the variable rats, you could do the following:
int rats;
int & rodents = rats; // makes rodents an alias for rats
In this context, & is not the address operator. Instead, it serves as part of the type identifier.
Just as char * in a declaration means pointer-to-char, int & means reference-to-int.
The reference declaration allows you to use rats and rodents interchangeably;
both refer to the same value and the same memory location.
Note that the & in int & rodents = rats; is not the address operator, but makes rodents of type int &, that is a reference to an int variable!
cout << ", rodents address = " << &rodents << endl;
Now in the example above & is used as address operator!
It is necessary to initialize the reference when you declare it; you can't declare the reference and then assign it a value later the way you can with a pointer.
int rat;
int & rodent;
rodent = rat; // No, you can't do this.!
rodent = rats;
Does not mean to make rodent a reference to rats, but copies the value of rats to rodent, also changing rat to that value.
In short, you can set a reference by an initializing declaration, not by assignment!
Suppose you tried the following:
int rats = 101;
int * pt = &rats;
int & rodents = *pt;
int bunnies = 50;
pt = &bunnies;
Initializing rodents to *pt makes rodents refer to rats. Subsequentely altering pt to point to bunnies does not alter the fact that rodents refers to rats.
inline functions
The compiler replaces the function call with the corresponding function code, instead of saving the return address, the address of the next instruction after the function call, and also the compiler does not store local variables on the stack. It places the function code inline with the other code.
With inline code, the program doesn' have to jump to another location to execute the code and then jump back.
Inline functions thus run a little faster than regular functions, but they come with a memory penalty.
If a program calls an inline function at 10 separate locations, then the program consists of 10 copies of the function inserted into code.
Recursion is not allowed for inline functions.
C users did make inline functions with macro's, one problem is with that that the functions are just expanded text, so no type checking is enforced by the compiler.
With inline code, the program doesn' have to jump to another location to execute the code and then jump back.
Inline functions thus run a little faster than regular functions, but they come with a memory penalty.
If a program calls an inline function at 10 separate locations, then the program consists of 10 copies of the function inserted into code.
Recursion is not allowed for inline functions.
C users did make inline functions with macro's, one problem is with that that the functions are just expanded text, so no type checking is enforced by the compiler.
zaterdag 23 juni 2007
Function Pointer, Pointer to Function.
To implement pointers to functions, you need to be able to do the following:
- Obtain the address of a function
- Declare a pointer to a function
- Use a pointer to a function to invoke the function
Obtaining the address of a function is simple, You just use the function name without trailing parentheses. That is, if think() is a function, then think is the address of the function.
Be sure you distinguish between passing the address of a function and passing the return value of a function:
process(think); // passes address of think() to process()
thought(think()); // passes return value of think() to thought()
Declaring a Pointer to a Function
The declaration of a pointer to a function should identify the function's return type and the function's signature (its argument list).
That is, the declaration of a pointer to a function should provide the same information about a function that a function prototype does. For example:
double pam(int); // prototype
Here's what a declaration of an approriate pointer type looks like:
double (*pf)(int); // pf points to a function that takes
// one int argument and that
// returns type double
Note that this looks just like the pam() declaration, with (*pf) playing the part of pam. Because pam is a function, so is (*pf). and if (*pf) is a function, then pf is a pointer to a function.
Tip:
In general, to declare a pointer to a particular kind of function, you can first write the prototype for a regular function if the desired kind, and then replace the function name with an expression in the form of (*pf). In this case, pf is a pointer to a function of that type.
The declaration requires the parentheses arround *pf to provide the proper operator precedence. Parentheses have a higher precedence than the * operator, so *pf(int) means pf() is a function that returns a pointer, whereas (*pf)(int) means pf is a pointer to a function:
double (*pf)(int); // pf points to a function that returns a double
double *pf(int); // pf() a function that returns a pointer-to-double
After you declare pf properly, you can assign to it the address of a matching function:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
Note that pam() has to match pf int both signature and return type. The compiler rejects non-matching assignments:
double ned(double);
int ted(int);
double (*pf)(int);
pf = ned; // invalid -- mismatched signature
pf = ted; // invalid -- mismatched return type
Example of a function declaration of a function that takes a function address as parameter:
void estimate(int lines, double (*pf)(int));
This declaration says the second argument is a pointer to a function that has an int argument and a double return value. To have estimate() use the pam() function, you pass pam()'s address to it:
estimate(50, pam); // function call telling estimate() to use pam()
Clearly, the tricky part about using pointers to functions is writing the prototypes, whereas passing the address is very simple.
Using a Pointer to Invoke a Function
Now we get to the final part of the technique, which is using a pointer to call the pointed-to-function. The clue comes in the pointer declaration. There, recall, (*pf) plays the same role as a function name. Thus, all you have to do is use (*pf) as if it were a function name:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
double x = pam(4); // call pam() using the function name
double y = (*pf)(5); // call pam() using the pointer pf
Actually, C++ also allows you to use pf as if it where a function name:
double y = pf(5); // also call pam() using the pointer pf
Using the first form is uglier, but provides a strong visual reminder that the code is using a function pointer.
/////////////////
Holy syntax! How can pf and (*pf) be equivalent?
a function name is an address concerned to C++ compiler,
func1(); to call it, where func1 is the address of func one, so it is dereferenced
automatically.
(*func1)(); dereference the function also, but now visible very much.
*func1(); will not dereference, but instead call func1() and then try to dereference the result, see this
* func1(); you see?
- Obtain the address of a function
- Declare a pointer to a function
- Use a pointer to a function to invoke the function
Obtaining the address of a function is simple, You just use the function name without trailing parentheses. That is, if think() is a function, then think is the address of the function.
Be sure you distinguish between passing the address of a function and passing the return value of a function:
process(think); // passes address of think() to process()
thought(think()); // passes return value of think() to thought()
Declaring a Pointer to a Function
The declaration of a pointer to a function should identify the function's return type and the function's signature (its argument list).
That is, the declaration of a pointer to a function should provide the same information about a function that a function prototype does. For example:
double pam(int); // prototype
Here's what a declaration of an approriate pointer type looks like:
double (*pf)(int); // pf points to a function that takes
// one int argument and that
// returns type double
Note that this looks just like the pam() declaration, with (*pf) playing the part of pam. Because pam is a function, so is (*pf). and if (*pf) is a function, then pf is a pointer to a function.
Tip:
In general, to declare a pointer to a particular kind of function, you can first write the prototype for a regular function if the desired kind, and then replace the function name with an expression in the form of (*pf). In this case, pf is a pointer to a function of that type.
The declaration requires the parentheses arround *pf to provide the proper operator precedence. Parentheses have a higher precedence than the * operator, so *pf(int) means pf() is a function that returns a pointer, whereas (*pf)(int) means pf is a pointer to a function:
double (*pf)(int); // pf points to a function that returns a double
double *pf(int); // pf() a function that returns a pointer-to-double
After you declare pf properly, you can assign to it the address of a matching function:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
Note that pam() has to match pf int both signature and return type. The compiler rejects non-matching assignments:
double ned(double);
int ted(int);
double (*pf)(int);
pf = ned; // invalid -- mismatched signature
pf = ted; // invalid -- mismatched return type
Example of a function declaration of a function that takes a function address as parameter:
void estimate(int lines, double (*pf)(int));
This declaration says the second argument is a pointer to a function that has an int argument and a double return value. To have estimate() use the pam() function, you pass pam()'s address to it:
estimate(50, pam); // function call telling estimate() to use pam()
Clearly, the tricky part about using pointers to functions is writing the prototypes, whereas passing the address is very simple.
Using a Pointer to Invoke a Function
Now we get to the final part of the technique, which is using a pointer to call the pointed-to-function. The clue comes in the pointer declaration. There, recall, (*pf) plays the same role as a function name. Thus, all you have to do is use (*pf) as if it were a function name:
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
double x = pam(4); // call pam() using the function name
double y = (*pf)(5); // call pam() using the pointer pf
Actually, C++ also allows you to use pf as if it where a function name:
double y = pf(5); // also call pam() using the pointer pf
Using the first form is uglier, but provides a strong visual reminder that the code is using a function pointer.
/////////////////
Holy syntax! How can pf and (*pf) be equivalent?
a function name is an address concerned to C++ compiler,
func1(); to call it, where func1 is the address of func one, so it is dereferenced
automatically.
(*func1)(); dereference the function also, but now visible very much.
*func1(); will not dereference, but instead call func1() and then try to dereference the result, see this
* func1(); you see?
vrijdag 22 juni 2007
Recursion
A C++ function has the interesting characteristic that it can call itself. (Unlike C, however C++ does not let main() call itself.) This ability is termed recursion. Recursion is an important tool in certain types of programming, such as artificial intelligengence, but we'll just take a superficial look (artificial shallowness) at how it works.
Recursion with a Single Recursive Call
If a recursive function calls itself, then the newly called function calls itself, and so on, ad infinitum unless the code includes something to terminate the chain of calls. The usual method is to make the recursive call part of an if statement. For example, a type void recursive function called recurs() can have a form like this:
void recurs(argumentlist)
{
statements1
if (test)
recurs(arguments)
statements2
}
With luck or foresight, test eventually becomes false, and the chains of calls is broken.
Recursive calls produce an intriguing chain of events. As long as the if statement remains true, each call to recurs() executes statements1 and then invokes a new incarnation of recurs() without reaching statements2. When the if statement becomes false, the current call then proceeds to statements2. Then when the current call terminates, program control returns to the previous version of recurs() that called it. Then, that version of recurs() completes executing its statements2 section and terminates, returning control to the prior call, and so on. Thus, if recurs() undergoes five recursive calls, first the statements1 section is executed five times in the order in which the functions where called, and then the statements2 section is executed five times in the opposite order from the order in which the were called. After going into five levels of recursion, the program then has to go back out through the same five levels.
Recursion with a Single Recursive Call
If a recursive function calls itself, then the newly called function calls itself, and so on, ad infinitum unless the code includes something to terminate the chain of calls. The usual method is to make the recursive call part of an if statement. For example, a type void recursive function called recurs() can have a form like this:
void recurs(argumentlist)
{
statements1
if (test)
recurs(arguments)
statements2
}
With luck or foresight, test eventually becomes false, and the chains of calls is broken.
Recursive calls produce an intriguing chain of events. As long as the if statement remains true, each call to recurs() executes statements1 and then invokes a new incarnation of recurs() without reaching statements2. When the if statement becomes false, the current call then proceeds to statements2. Then when the current call terminates, program control returns to the previous version of recurs() that called it. Then, that version of recurs() completes executing its statements2 section and terminates, returning control to the prior call, and so on. Thus, if recurs() undergoes five recursive calls, first the statements1 section is executed five times in the order in which the functions where called, and then the statements2 section is executed five times in the opposite order from the order in which the were called. After going into five levels of recursion, the program then has to go back out through the same five levels.
-> the indirect membership operator
If you use a pointer to a struct, you can't use the membership operator, the dot
struct xy
{
int x;
int y;
}
now create a structure
xy aPos;
aPos.x = 10;
aPos.y = 20;
But when using a pointer to the struct:
xy * pxyPos;
pxyPos = &aPos;
You have to use the indirect membership operator
pxyPos->x = 20;
pxyPos->y = 30;
struct xy
{
int x;
int y;
}
now create a structure
xy aPos;
aPos.x = 10;
aPos.y = 20;
But when using a pointer to the struct:
xy * pxyPos;
pxyPos = &aPos;
You have to use the indirect membership operator
pxyPos->x = 20;
pxyPos->y = 30;
arr[i] and &arr[i]
arr[i] == *(arr + i) // values in two notations
&arr[i] == arr + i // addresses in two notations
Remember that adding one to a pointer, including an array name, actually adds a value equal to the size, in bytes, of the type to which the pointer points.
Pointer addition and array subscription are two equivalent ways of counting elements from the beginning of an array.
&arr[i] == arr + i // addresses in two notations
Remember that adding one to a pointer, including an array name, actually adds a value equal to the size, in bytes, of the type to which the pointer points.
Pointer addition and array subscription are two equivalent ways of counting elements from the beginning of an array.
donderdag 21 juni 2007
Pointers
A pointer is a value that represents the address of an object. Every distinct object has a unique address, which denotes the part of the computer's memory that contains the object. If you can access an object, you can obtain its address, and vice versa, so if we have an address we can access the object.
For example if x is an object, then &x is the address of that object, and if p is the address of an object, then *p is the object itself. The & in &x is an address operator, and is distinct from the use of & to define reference types. The * is a dereference operator, which works analogously to the way * works when applied to another iterator. If p contains the address of x, we also say that p is a pointer that points to x. It is common to represent such a state of affairs with a diagram such as:
p---->x
As with other built-in types, a local variable that is a pointer has no meaningful value until we give it one. Programmers frequently use the value 0 to initialize pointers, because converting 0 to a pointer yields a value that is guaranteed to be distinct from a pointer to any object. Moreover, the constant 0 is the only integer value that can be converted to a pointer type. The resulting value, often called a null pointer, is often useful in comparisons.
As with all C++ values, pointers have types. The address of an object of type T has type "pointer to T", written as T* in definitions and similar contexts.
Suppose that x us an object of type int, defined as
int x;
and we want to define p to have a type that will allow p to contain the address of x. We do so by saying that the type of p is "pointer to int", which we say implicitly by defining *p to have type int:
int *p; // *p has type int
Here *p is a declarator, which is the part of a definition that defines a single variable. Even though the * and the p are part of a single declarator, most C++ programmers write this definition as:
int* p; // p has type int
to emphasize the notion that p has a particular type (i.e, int*). These uses are equivalent because the spaces around the * are neutral. However the latter usage conceals a pitfall that is so important that it deserves special attention:
int* p, q; // what does this definition mean?
defines p as an object of type "pointer to int", and q as an object of type int. This example is easier to understand if we view it this way:
int *p, q;
or int (*p), q;
Still better, we can make our intentions crystal clear by writing
int* p;
int q;
We now know enough to write a simple program that uses pointers:
int main()
{
int x = 5;
// p points to x
int* p = &x;
cout << "x = " << p =" 6;" x =" " x =" 5" x =" 6">5
It should be no surprise that x is 5 when we execute the first output expression. The next statement changes the value of x to 6 by executing *p = 6. Remember, once p contains the address of x, *p and x are two different ways of referring to the same object. Thus, the x is 6 when the second output expression is executed.
It may be useful to think of a pointer to an object as an iterator that refers to the only element of a "container" that contains the object and nothing else.
Arrays
An array is a kind of container that is part of the core language rather then part of the standard library. Every array contains a sequence of one or more objects of the same type. The number of elements in the array must be known at compile time, which requirement implies that arrays cannot grow or shrink dynamically the way the library containers do.
Because arrays are not class types, they have no members. In particular the do not have the size_type member to name an appropriate type to deal with the size of an array. Instead, theheader defines size_t, which is a more general type. The implementation defines size_t as the appropriate unsigned type large enough to hold the size of any object. Thus, we can (and should) use size_type to deal with the size of a container.
For example, a three dimensional geometry program might represent a point this way:
double coords[3];
knowing that the number of dimensions in physical space is unlike to change any time soon. A more experienced programmer might represent the point this way:
const size_t NDim = 3;
double coords[NDim];
taking advances, for documentation purposes, of the fact that the value of NDim is known at compilation time (because it is a const size_t that is initialized from a constant). Using NDim instead of 3 distinguishes the 3 that represents the number of dimensions from a 3 that represents, say the number of sides in a triangle.
For example if x is an object, then &x is the address of that object, and if p is the address of an object, then *p is the object itself. The & in &x is an address operator, and is distinct from the use of & to define reference types. The * is a dereference operator, which works analogously to the way * works when applied to another iterator. If p contains the address of x, we also say that p is a pointer that points to x. It is common to represent such a state of affairs with a diagram such as:
p---->x
As with other built-in types, a local variable that is a pointer has no meaningful value until we give it one. Programmers frequently use the value 0 to initialize pointers, because converting 0 to a pointer yields a value that is guaranteed to be distinct from a pointer to any object. Moreover, the constant 0 is the only integer value that can be converted to a pointer type. The resulting value, often called a null pointer, is often useful in comparisons.
As with all C++ values, pointers have types. The address of an object of type T has type "pointer to T", written as T* in definitions and similar contexts.
Suppose that x us an object of type int, defined as
int x;
and we want to define p to have a type that will allow p to contain the address of x. We do so by saying that the type of p is "pointer to int", which we say implicitly by defining *p to have type int:
int *p; // *p has type int
Here *p is a declarator, which is the part of a definition that defines a single variable. Even though the * and the p are part of a single declarator, most C++ programmers write this definition as:
int* p; // p has type int
to emphasize the notion that p has a particular type (i.e, int*). These uses are equivalent because the spaces around the * are neutral. However the latter usage conceals a pitfall that is so important that it deserves special attention:
int* p, q; // what does this definition mean?
defines p as an object of type "pointer to int", and q as an object of type int. This example is easier to understand if we view it this way:
int *p, q;
or int (*p), q;
Still better, we can make our intentions crystal clear by writing
int* p;
int q;
We now know enough to write a simple program that uses pointers:
int main()
{
int x = 5;
// p points to x
int* p = &x;
cout << "x = " << p =" 6;" x =" " x =" 5" x =" 6">5
It should be no surprise that x is 5 when we execute the first output expression. The next statement changes the value of x to 6 by executing *p = 6. Remember, once p contains the address of x, *p and x are two different ways of referring to the same object. Thus, the x is 6 when the second output expression is executed.
It may be useful to think of a pointer to an object as an iterator that refers to the only element of a "container" that contains the object and nothing else.
Arrays
An array is a kind of container that is part of the core language rather then part of the standard library. Every array contains a sequence of one or more objects of the same type. The number of elements in the array must be known at compile time, which requirement implies that arrays cannot grow or shrink dynamically the way the library containers do.
Because arrays are not class types, they have no members. In particular the do not have the size_type member to name an appropriate type to deal with the size of an array. Instead, the
For example, a three dimensional geometry program might represent a point this way:
double coords[3];
knowing that the number of dimensions in physical space is unlike to change any time soon. A more experienced programmer might represent the point this way:
const size_t NDim = 3;
double coords[NDim];
taking advances, for documentation purposes, of the fact that the value of NDim is known at compilation time (because it is a const size_t that is initialized from a constant). Using NDim instead of 3 distinguishes the 3 that represents the number of dimensions from a 3 that represents, say the number of sides in a triangle.
woensdag 20 juni 2007
Functions and Two-Dimensional Arrays
To write a function that has a two-dimensional array as argument, you need to remember that the name of an array is treated as its address, so the corresponding formal parameter is a pointer, just as for one-dimensional arrays. The tricky part is declaring the pointer correctly.
Suppose, for example, that you start with this code:
int data[3][4] = {{1,2,3,4}, {9,8,7,6}, {2,4,6,8}};
int total = sum(data, 3);
What should the prototype for sum() look like? And why does the function pass the number of rows (3) as an argument and not also the number of columns(4)?
Well, data is the name of an array with three elements. The first element is, itself, an array of four int values. Thus, the type of data is pointer-to-array-of-four-int, so an appropiate prototype would be this:
int sum(int (*ar2)[4], int size);
The parentheses are needed because the declaration
int *ar2[4]
Would declare an array of four pointers-to-int instead of a singe pointer-to-array-of-four-int, and a function parameter cannot be an array.
There's an alternative format that means exactly the same thing as this first prototype, but perhaps it is easier to read:
int sum(int ar2[][4], int size);
Either prototype states that ar2 is a pointer, not an array. Also note that the pointer type specifically says it points to an array of four ints. Thus, the pointer type specifies the numbert of columns, which is why the number of columns is not passed as a separate function argument.
Because the pointer type specifies the number of columns, the sum() function only works with arrays with four columns, But the number of rows is specified by the variable size, so sum() can work with a variying number of rows:
int a[100][4];
int b[6][4];
...
int total1 = sum(a, 100); // sum all of a
int total2 = sum(b, 6); // sum all of b
int total3 = sum(a, 10); // sum first 10 rows of a
int total4 = sum(a+10, 20); // sum next 20 rows of a
given that the parameter ar2 is a pointer to an array, how do you use it in the function definition? The simplest way is to use ar2 as if it where the name of a two-dimensional array, Here's a possible function definition:
int sum(int ar2[][4], int size)
{
int total = 0;
for (int r = 0; r < size; r++)
for (int c = 0; c < 4; c++)
total += ar2[r][c];
return total;
}
Again, note that the number of rows is whatever is passed to the size parameter, but the number of columns is fixed at four, both in the parameter declaration for ar2 and in the inner for loop.
Here is why you can use array notation. Because ar2 points to the first element(element 0) of an array whose elements are array-of-four-int, the expression ar2 + r points to the element number r. Therefor ar2[r] is element number r. That element is itself an array-of-four-int, so ar2[r] is the name of that array-of-four-int. Applying a subscript to an array name gives an array element, so ar2[r][c] is an element of the array-of-four-int, hence is a single int value.
The pointer ar2 has to be dereferenced twice to get the data. The simplest way is to use the brackets twice, as in ar2[r][c]. But it is possible, if ungainly, to use the * operator twice:
ar2[r][c] == *(*(ar2 + r) + c) // same thing
To understand this, you can work out the meaning of the subexpressions from inside out:
ar2 // pointer to first row of an array of 4 int
ar2 + r // pointer to row r (an array of 4 int)
*(ar2 + r) // row r (an array of 4 int, hence the name of an array,
// thus a pointer to the first int in the row, i.e., ar2[r]
*(ar2 +r) + c // pointer int number c in row r, i.e., ar2[r] + c
*(*ar2 + r) + c // value of int number c in row r, i.e. ar2[r][c]
Incidentally, the code for sum() does not use const in declaring the parameter ar2 because that technique is for pointers to fundamental types, and ar2 is a pointer to a pointer.
Suppose, for example, that you start with this code:
int data[3][4] = {{1,2,3,4}, {9,8,7,6}, {2,4,6,8}};
int total = sum(data, 3);
What should the prototype for sum() look like? And why does the function pass the number of rows (3) as an argument and not also the number of columns(4)?
Well, data is the name of an array with three elements. The first element is, itself, an array of four int values. Thus, the type of data is pointer-to-array-of-four-int, so an appropiate prototype would be this:
int sum(int (*ar2)[4], int size);
The parentheses are needed because the declaration
int *ar2[4]
Would declare an array of four pointers-to-int instead of a singe pointer-to-array-of-four-int, and a function parameter cannot be an array.
There's an alternative format that means exactly the same thing as this first prototype, but perhaps it is easier to read:
int sum(int ar2[][4], int size);
Either prototype states that ar2 is a pointer, not an array. Also note that the pointer type specifically says it points to an array of four ints. Thus, the pointer type specifies the numbert of columns, which is why the number of columns is not passed as a separate function argument.
Because the pointer type specifies the number of columns, the sum() function only works with arrays with four columns, But the number of rows is specified by the variable size, so sum() can work with a variying number of rows:
int a[100][4];
int b[6][4];
...
int total1 = sum(a, 100); // sum all of a
int total2 = sum(b, 6); // sum all of b
int total3 = sum(a, 10); // sum first 10 rows of a
int total4 = sum(a+10, 20); // sum next 20 rows of a
given that the parameter ar2 is a pointer to an array, how do you use it in the function definition? The simplest way is to use ar2 as if it where the name of a two-dimensional array, Here's a possible function definition:
int sum(int ar2[][4], int size)
{
int total = 0;
for (int r = 0; r < size; r++)
for (int c = 0; c < 4; c++)
total += ar2[r][c];
return total;
}
Again, note that the number of rows is whatever is passed to the size parameter, but the number of columns is fixed at four, both in the parameter declaration for ar2 and in the inner for loop.
Here is why you can use array notation. Because ar2 points to the first element(element 0) of an array whose elements are array-of-four-int, the expression ar2 + r points to the element number r. Therefor ar2[r] is element number r. That element is itself an array-of-four-int, so ar2[r] is the name of that array-of-four-int. Applying a subscript to an array name gives an array element, so ar2[r][c] is an element of the array-of-four-int, hence is a single int value.
The pointer ar2 has to be dereferenced twice to get the data. The simplest way is to use the brackets twice, as in ar2[r][c]. But it is possible, if ungainly, to use the * operator twice:
ar2[r][c] == *(*(ar2 + r) + c) // same thing
To understand this, you can work out the meaning of the subexpressions from inside out:
ar2 // pointer to first row of an array of 4 int
ar2 + r // pointer to row r (an array of 4 int)
*(ar2 + r) // row r (an array of 4 int, hence the name of an array,
// thus a pointer to the first int in the row, i.e., ar2[r]
*(ar2 +r) + c // pointer int number c in row r, i.e., ar2[r] + c
*(*ar2 + r) + c // value of int number c in row r, i.e. ar2[r][c]
Incidentally, the code for sum() does not use const in declaring the parameter ar2 because that technique is for pointers to fundamental types, and ar2 is a pointer to a pointer.
Pointers and const
Using const with pointers has some subtle aspects (pointers always seem to have subtle aspects), so let's take a closer look.
You can use the const keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself a constant, and that prevents you from changing where the pointer points.
First, let's declare a pointer pt that points to a constant:
int age = 39;
const int * pt = &age;
This declaration states that pt points to a const int(39, in this case). Therefor, you can't use pt to change that value. In other words, the value *pt is const and cannot be modified:
*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason
Now for a subtle point. This declaration for pt doesn't necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt is concerned.
For example, pt points to age, and age is not const. You can change the value of age directly by using the age variable, but you can't change the value indirectly via the pt pointer:
*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const
In the past, you've assigned the address of a regular variable to a regular pointer. Now you've assigned the address of a regular variable to a pointer-to-const. That leaves two other possibilities: assigning the address of a const variable to a pointer-to-const and assigning the address of a const to a regular pointer. Are they both possible? The first is, and the second isn't:
const float g_earth = 9.80;
const float * pe = &g_earth; // VALID
const float g_moon = 1.63;
float * pm = &g_moon; // INVALID
For the first case, you can use neither g_earth nor pe to change the value 9.80. C++ doesn't allow the second case for a simple reason: If you assign the address of g_moon to pm, then you can cheat and use pm to alter the value of g_moon.
That makes a mockery of g_moon's const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.
(if you are really desperate, you can use a type cast to override the restriction; see const_cast operator)
The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const pointer to a const pointer is okay, provided that you're dealing with just one level of indirection:
int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an INVALID operation
But pointer assignments that mix const and non-const in this manner are NO longer SAFE when you go to two levels of indirection. If mixing const and non-const were allowed, you could do something like this:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n
Suppose you have an array of const data:
const int months[12] = {31,28,31,30,31,,30,31,31,30,31,30,31};
The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-const formal argument:
int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // NOT allowed
This function call attempts to assign a const pointer (months) to a non-const pointer (arr), and the compiler disallows the function call.
Using const When You Can
There are two strong reasons to declare pointer arguments as pointers to constant data:
- It protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype can accept
only non-const data.
You should declare formal pointer arguments as pointers to const whenever it's appropriate to do so.
For yet another subtle point, consider the following declarations:
int age = 39;
const int * pt = &age;
The const in the second declaration only prevents you from changing the value to which pt points, which is 39. It does not prevent you from changing the value of pt itself. That is, you can assign a new value to pt:
int sage = 80;
pt = &sage; // okay to point to another location'
But you still can't use pt to change the value to which it points(now 80)
The second way to use const makes it impossible to change the value of the pointer itself:
int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; a const pointer to int
Note that the last declaration has repositioned the keyword const. This form of declaration constrains finger to point only to sloth. However, it allows you to use finger to alther the value of sloth. The middle declaration does not allow you to use ps to alter the value of sloth, but it permits you to have ps point to another location. In short, finger and *ps are both const, and *finger and ps are not const.
If you like, you can declare a const pointer to a const object:
double trouble = 2.0E30;
const double * const stick = &trouble;
Here stick can point only to trouble, and stick cannot be used to change the value of trouble. In short both stick and *stick are const.
Typically you use the pointer to const form to protect data when you pass pointers as function arguments. For example:
void show_array(const double ar[], int n);
Using const in this declaration means that show_array() cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here for example, the array elements are fundamental type, but if they where pointers or pointers-to-pointers, you wouldn't use const.
You can use the const keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself a constant, and that prevents you from changing where the pointer points.
First, let's declare a pointer pt that points to a constant:
int age = 39;
const int * pt = &age;
This declaration states that pt points to a const int(39, in this case). Therefor, you can't use pt to change that value. In other words, the value *pt is const and cannot be modified:
*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason
Now for a subtle point. This declaration for pt doesn't necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt is concerned.
For example, pt points to age, and age is not const. You can change the value of age directly by using the age variable, but you can't change the value indirectly via the pt pointer:
*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const
In the past, you've assigned the address of a regular variable to a regular pointer. Now you've assigned the address of a regular variable to a pointer-to-const. That leaves two other possibilities: assigning the address of a const variable to a pointer-to-const and assigning the address of a const to a regular pointer. Are they both possible? The first is, and the second isn't:
const float g_earth = 9.80;
const float * pe = &g_earth; // VALID
const float g_moon = 1.63;
float * pm = &g_moon; // INVALID
For the first case, you can use neither g_earth nor pe to change the value 9.80. C++ doesn't allow the second case for a simple reason: If you assign the address of g_moon to pm, then you can cheat and use pm to alter the value of g_moon.
That makes a mockery of g_moon's const status, so C++ prohibits you from assigning the address of a const to a non-const pointer.
(if you are really desperate, you can use a type cast to override the restriction; see const_cast operator)
The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const pointer to a const pointer is okay, provided that you're dealing with just one level of indirection:
int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an INVALID operation
But pointer assignments that mix const and non-const in this manner are NO longer SAFE when you go to two levels of indirection. If mixing const and non-const were allowed, you could do something like this:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n
Suppose you have an array of const data:
const int months[12] = {31,28,31,30,31,,30,31,31,30,31,30,31};
The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-const formal argument:
int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // NOT allowed
This function call attempts to assign a const pointer (months) to a non-const pointer (arr), and the compiler disallows the function call.
Using const When You Can
There are two strong reasons to declare pointer arguments as pointers to constant data:
- It protects you against programming errors that inadvertently alter data
- Using const allows a function to process both const and non-const actual arguments, whereas a function that omits const in the prototype can accept
only non-const data.
You should declare formal pointer arguments as pointers to const whenever it's appropriate to do so.
For yet another subtle point, consider the following declarations:
int age = 39;
const int * pt = &age;
The const in the second declaration only prevents you from changing the value to which pt points, which is 39. It does not prevent you from changing the value of pt itself. That is, you can assign a new value to pt:
int sage = 80;
pt = &sage; // okay to point to another location'
But you still can't use pt to change the value to which it points(now 80)
The second way to use const makes it impossible to change the value of the pointer itself:
int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; a const pointer to int
Note that the last declaration has repositioned the keyword const. This form of declaration constrains finger to point only to sloth. However, it allows you to use finger to alther the value of sloth. The middle declaration does not allow you to use ps to alter the value of sloth, but it permits you to have ps point to another location. In short, finger and *ps are both const, and *finger and ps are not const.
If you like, you can declare a const pointer to a const object:
double trouble = 2.0E30;
const double * const stick = &trouble;
Here stick can point only to trouble, and stick cannot be used to change the value of trouble. In short both stick and *stick are const.
Typically you use the pointer to const form to protect data when you pass pointers as function arguments. For example:
void show_array(const double ar[], int n);
Using const in this declaration means that show_array() cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here for example, the array elements are fundamental type, but if they where pointers or pointers-to-pointers, you wouldn't use const.
Functions Using Array ranges
The STL approach uses the concept of "one past the end" to indicate an extent. That is, in the case of an array, the argument identifying the end of the array would be a pointer to the location just after the last element. For example, suppose you have this declaration:
double elbuod[20]
Then the two pointers elboud and elboud + 20 define the range. First, elboub, being the name of the array, points to the first element. The expression elboud + 19 points to the last element (that is, elboud[19]), so elboud + 20 points to one past the end of the array. Passing a range to a function tells it which elements to process.
Example:
for (pt = begin; pt != end; pt++)
total = total + *pt;
here begin is a pointer to the first element of an array
here end is a pointer one past the end from the array, easy because you can give the size of the array as end value pointer
int sum = sum_arr(cookies, cookies + ArSize);
so the end is cookies array address + ArSize, which is the array size, which is always one to much because arrays start counting at zero, in this case to 7, but the size is counted from 1 to 8 so 8 is one past the end.
Note by the way that rules for pointer subtraction imply that, in sum_arr(), the expression end - begin is an integer value equal to the number of elements in the range.
So 8 - 0 = 8, so there are 8 elements in the array!
double elbuod[20]
Then the two pointers elboud and elboud + 20 define the range. First, elboub, being the name of the array, points to the first element. The expression elboud + 19 points to the last element (that is, elboud[19]), so elboud + 20 points to one past the end of the array. Passing a range to a function tells it which elements to process.
Example:
for (pt = begin; pt != end; pt++)
total = total + *pt;
here begin is a pointer to the first element of an array
here end is a pointer one past the end from the array, easy because you can give the size of the array as end value pointer
int sum = sum_arr(cookies, cookies + ArSize);
so the end is cookies array address + ArSize, which is the array size, which is always one to much because arrays start counting at zero, in this case to 7, but the size is counted from 1 to 8 so 8 is one past the end.
Note by the way that rules for pointer subtraction imply that, in sum_arr(), the expression end - begin is an integer value equal to the number of elements in the range.
So 8 - 0 = 8, so there are 8 elements in the array!
Display an array with a function
Building a function to display the array is simple. You pass the name of the array and the number of filled elements to the function, which then uses a loop to display each element.
But there is another consideration--guaranteeing that the display function doesn't alter the original array.
Unless the purpose of a function is to alter data passed to it, you should safeguard it from doing so. That protection comes automaticaly with ordinary arguments because C++ passes them by value, and the function works with a copy. But functions that use an array work with the original.
To keep a function from accidently altering the contents of an array argument, you can use the keyword CONST when you declare the formal argument:
void show_array(const double ar[], int n);
The declaration states that the pointer ar points to constant data. This means that you can't use ar to change the data. That is, you can use a value such as ar[0], but you can't change that value. Thus, show_array() treats the array as read-only data.
If you try to modify const data, your compiler will create an error and a message describing what you tried to do.
This is the code for the show_array() function:
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; ++i)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
But there is another consideration--guaranteeing that the display function doesn't alter the original array.
Unless the purpose of a function is to alter data passed to it, you should safeguard it from doing so. That protection comes automaticaly with ordinary arguments because C++ passes them by value, and the function works with a copy. But functions that use an array work with the original.
To keep a function from accidently altering the contents of an array argument, you can use the keyword CONST when you declare the formal argument:
void show_array(const double ar[], int n);
The declaration states that the pointer ar points to constant data. This means that you can't use ar to change the data. That is, you can use a value such as ar[0], but you can't change that value. Thus, show_array() treats the array as read-only data.
If you try to modify const data, your compiler will create an error and a message describing what you tried to do.
This is the code for the show_array() function:
void show_array(const double ar[], int n)
{
using namespace std;
for (int i = 0; i < n; ++i)
{
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
Functions and Arrays
The sample functions I talked about in some previous blogs are very simple, basic. They only use build in data types for arguments and return values.
But now let's talk about functions that uses arrays and structures as argument or return type.
Suppose you use an array to keep track of how many cookies each person has eaten at a family picnic. (each array index corresponds to a person, and the value of the element corresponds to the number of cookies that person has eaten.) Now you want the total. That's easy to find; you just loop to add all the array elements. But adding array elements is such a common task that it makes sense to design a function for the job.
Then you don't have to write a new loop everythime you have to sum an array.
int sum_arr(int arr[], int n) // arr = array name, n = size
This looks plausible. The brackets seem to indicate that arr is an array, and the fact that the brackets are empty seems to indicate that you can use the function with an array of any size.
BUT THINGS ARE NOT ALWAYS AS THEY SEEM!
arr is not really an array, it's a pointer!
The good news is that you can write the rest of the function just as if arr were an array.
here is the function:
// return the sum of an integer array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < total =" total" cookies ="="" sum =" sum_arr(cookies," arr =" array" n =" size" i =" 0;">> temp;
if (!cin) // bad input
{
cin.clear()
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp =< 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
Note that this code includes a prompt to the user. If the user enters a non-negative value, the value is assigned to the array. Otherwise the loop terminates. If the user enters only valid values, the loop terminates after it reads limit values. The last thing the loop does is incrementing i, so after the loop terminate, i is one greater then the last array index, hence it's equal to the number of filled elements. The function returns that value.
But now let's talk about functions that uses arrays and structures as argument or return type.
Suppose you use an array to keep track of how many cookies each person has eaten at a family picnic. (each array index corresponds to a person, and the value of the element corresponds to the number of cookies that person has eaten.) Now you want the total. That's easy to find; you just loop to add all the array elements. But adding array elements is such a common task that it makes sense to design a function for the job.
Then you don't have to write a new loop everythime you have to sum an array.
int sum_arr(int arr[], int n) // arr = array name, n = size
This looks plausible. The brackets seem to indicate that arr is an array, and the fact that the brackets are empty seems to indicate that you can use the function with an array of any size.
BUT THINGS ARE NOT ALWAYS AS THEY SEEM!
arr is not really an array, it's a pointer!
The good news is that you can write the rest of the function just as if arr were an array.
here is the function:
// return the sum of an integer array
int sum_arr(int arr[], int n)
{
int total = 0;
for (int i = 0; i < total =" total" cookies ="="" sum =" sum_arr(cookies," arr =" array" n =" size" i =" 0;">> temp;
if (!cin) // bad input
{
cin.clear()
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp =< 0) // signal to terminate
break;
ar[i] = temp;
}
return i;
}
Note that this code includes a prompt to the user. If the user enters a non-negative value, the value is assigned to the array. Otherwise the loop terminates. If the user enters only valid values, the loop terminates after it reads limit values. The last thing the loop does is incrementing i, so after the loop terminate, i is one greater then the last array index, hence it's equal to the number of filled elements. The function returns that value.
Two kinds of local variables
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}
The probability() function illustrates two kinds of local variables you can have in a function. First there are the formal parameters (numbers and picks), which are declared in the function header before the opening brace. Then come the other local variables (result, n and p). They are declared in between the braces bounding the function definition.
The main difference between the formal parameters and the other local variables is that the formal parameters get their values from the function that calls probability(), whereas the other variables get values from within the function.
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}
The probability() function illustrates two kinds of local variables you can have in a function. First there are the formal parameters (numbers and picks), which are declared in the function header before the opening brace. Then come the other local variables (result, n and p). They are declared in between the braces bounding the function definition.
The main difference between the formal parameters and the other local variables is that the formal parameters get their values from the function that calls probability(), whereas the other variables get values from within the function.
Something about cin >> ch and cin.get()
In a example in my book they used cin >> ch, instead of using cin.get(ch) or ch = cin.get().
The reason is that cin >> ch, skips all whitespace including '\n'.
cin.get(ch) will read all input characters, including spaces and newlines.
So it is often more easy to use cin >> ch then using cin.get(), however ofcourse you can program arround the cin.get() behaviour.
The reason is that cin >> ch, skips all whitespace including '\n'.
cin.get(ch) will read all input characters, including spaces and newlines.
So it is often more easy to use cin >> ch then using cin.get(), however ofcourse you can program arround the cin.get() behaviour.
Multiple Arguments to functions
A function can have more than one argument. In the function call, you separate the arguments with commas:
n_chars('R', 25);
This passes two arguments to the function n_chars().
Similarly, when you define the function, you use a comma-seperated list of parameter declarations in the function header:
void n_chars(char c, int n) // two arguments
This function header states that the function n_chars() takes one type char argument and one type int argument. The parameters c and n are assigned the values passed to the function.
If a function has two parameters of the same type, you have to give the type of each parameter seperately.
void fifi(float a, float b) // declare each variable separately
void fufu(float a, b) // NOT acceptable
As with other functions, you just add a semicolon to get a prototype
void n_chars(char c, int n); // prototype, style 1
void n_chars(char, int); // prototype style 2
However, providing variable names can make the prototype more understandable, particularly if two parameters are the same type. Then, the names can remind you which argument is which:
double melon_density(double weight, double volume);
n_chars('R', 25);
This passes two arguments to the function n_chars().
Similarly, when you define the function, you use a comma-seperated list of parameter declarations in the function header:
void n_chars(char c, int n) // two arguments
This function header states that the function n_chars() takes one type char argument and one type int argument. The parameters c and n are assigned the values passed to the function.
If a function has two parameters of the same type, you have to give the type of each parameter seperately.
void fifi(float a, float b) // declare each variable separately
void fufu(float a, b) // NOT acceptable
As with other functions, you just add a semicolon to get a prototype
void n_chars(char c, int n); // prototype, style 1
void n_chars(char, int); // prototype style 2
However, providing variable names can make the prototype more understandable, particularly if two parameters are the same type. Then, the names can remind you which argument is which:
double melon_density(double weight, double volume);
Abonneren op:
Posts (Atom)