- In addition to the three member functions that we looked at
in the last class, there is an additional member function called
Time()
- The name of this member function is the same as the name of
the type. This is a special member function called constructor.
- Constructor doesn't have a return type. This does NOT mean
that its return type is void
- Constructor is called automatically and only once when a variable
of that type is declared
- Time t; // this declaration also calls constructor
- The constructor Time in Fig. 6.3 initializes the data members
to zero. Typically, a constructor does the initialization of data
members.
- In a C++ class, both data and function members can be private
or public
- Private members are accessible only in the member functions.
Public members are accessible in any function.
- If you write code such as t.hour = 78; in the main function,
you will get an error message.
- This restricts the access to certain members
- Generally, data members are put in the private portion. But
C++ allows you to put data members in the public portion.
- Makes sure that anyone using the data type doesn't make arbitrary
assignments. For example t.hour = 78; is clearly not a desirable
assignment. Since the users don't have direct access to the data
members, they can never set the value of hour data member to be
anything other than a value between 0 and 23.
- t.setTime(78,0,0); // setTime will set the value of hour to
be equal to 0 instead of 78.
- By default all members in a class in C++ are private.
- By default all members in a struct in C++ are public.
- You can change the defaults by typing either public: or private:
- Once you type private: all the members will be private until
you type public: and vice versa.
- Your book prefers to type in the public: members before the
private: members.
- We looked at various components of an existing user defined
type.
- In order to create a user-defined type, we need to understand
the syntax.
- We want to create an essentially useless class called useless.
class <type-name>
{
......
};
class useless
{
};
- let us add a function member to this class. We will add the
constructor. The constructor will have just an output statement
"A variable of the type useless is created." Name of
the constructor will be useless()
- We will also add a destructor. The name of the destructor
is ~ followed by the <type-name>. In our example, ~useless()
- Similar to constructor, destructor is never explicitly called.
It is automatically called when the variable goes out of scope.
Let our destructor display a message "A variable of the type
useless is destructed."
- Look at useless.cpp
- The constructor is executed when u is declared. The destructor
is executed when program reaches the closing brace.