Programming and Graphics

(Kiana) #1

6.3 Class definition 155


fruit(q, w, ..., e);
...
private:
...
};

Like the default constructor, the parametered constructor does not have a return
type, not evenvoid. The name of the parametered constructor is identical to
the class name.


To define a fruit named “kiwi” using the parametered constructor, we
state in the main program:


fruit kiwi;
kiwi = fruit(qvalue, wvalue, ..., qvalue);

or


fruit kiwi = fruit(qvalue, wvalue, ..., qvalue);

or


fruit kiwi(qvalue, wvalue, ..., qvalue);

Two constructors


Since the default and parametered constructors have identical names,
they are distinguished only by the number and type of arguments enclosed
by the parentheses. This duplication is consistent with the notion of function
overloading: two functions with the same name are distinguished by the data
types of their arguments.


Defining a class constructor is not mandatory. If we do not declare a
constructor in the class definition, the compiler will assume that the class has
a default constructor with no arguments. However, it is a good idea to always
define a constructor.


Default destructor


The declaration of the default destructor is similar to that of the default
constructor. The class definition with the default constructor, the parametered
constructor, and the default destructor reads:


class fruit
{
Free download pdf