Classes -- Constructors
class myClass {
public:
myClass();
myClass(const
myClass &);
myClass(const
int, const int,
const string &, const char *);
myClass
& operator=(const myClass &);
private:
...
}
CS151 -- Shawn Stoffer
Classes -- Identifying Constructors
-
They are always simply the class name and arguments to the
constructor.
-
The class name takes the place of, is, the function name.
-
A method which has the same name as the class
CS151 -- Shawn Stoffer
-
There are many types, though specifically, there are really
only three types.
-
Default
-
Copy
-
Other (special purpose)
CS151 -- Shawn Stoffer
Classes -- The Default Constructor
myClass();
-
Identification
-
Usage
-
Is called whenever you declare this type of variable without
specifying another constructor.
CS151 -- Shawn Stoffer
Classes -- The Copy Constructor
myClass(const
myClass &);
-
Identification
-
Its one argument (type) is the class.
-
Usage
-
Is called whenever
-
You declare a variable of this type using the assignment
operator (=)
myClass j;
myClass m = j; //
<--------
-
You use the constructor notation with another variable of
this class type.
myClass j;
myClass m(j); //
<--------
CS151 -- Shawn Stoffer
Classes -- The Copy Constructor
myClass(const
int, const int,
const string &, const char *);
-
Identification
-
It has any number of arguments
-
no specific type
-
Usage
-
Is called only when it is called directly...
myClass m(3, 4, "Directly", "because");
or
myClass m;
...
m = myClass(3, 4, "Directly", "later");
CS151 -- Shawn Stoffer
Classes -- The Assignment Operator
myClass
& operator=(const myClass &);
-
Identification
-
It uses operator overloading, otherwise looks quite similar
to the copy constructor.
-
Usage
-
Just as you would use the normal = operator.
myClass m, j(5,4,"Example", "assignment");
m = j;
CS151 -- Shawn Stoffer
Review -- Const
myClass(const myClass &);
myClass(const
int, const int,
const string &, const char *);
myClass & operator=(const
myClass &);
Why use const?
The parameter is not changing, and further SHOULD NOT change.
CS151 -- Shawn Stoffer
Review -- Reference Parameters
myClass(const myClass &);
myClass(const
int, const int,
const string &, const char *);
myClass & operator=(const
myClass &);
Why use reference parameters (myClass &, string &)?
The parameter is an object
Objects can be quite large
Passing by value COPIES the object when the function is called
large objects take a long time to copy
CS151 -- Shawn Stoffer