10. Default class members, conversion constructors, conversion operators
07/03/23
Default Member Functions
- Default constructor (no parameters needed)
- Constructor which takes no parameters.
- The generated default constructor is empty
- Why you can still create objects even when classes appear to have no constructors
- Use
ClassName() = default;
to stop it
- Copy constructor (cone one object to another)
- Used to initialise one object from another of the same type.
- Returning object by value from a function
- A copy constructor is created by default
- Default behaviour copies each member in turn.
- An assignment operator (= operator)
- Used when value of one object is assigned to another.
- Create your own using operator overloading
- Takes a reference to the one we are getting values from
- A destructor
- Created if you do not create one
- Gets called as members get destroyed
- Basic data types just get destroyed
- Pointers just get destroyed
General Rules
- If need a copy constructor, or an assignment operator, then probably need to create the other, plus a destructor as well
Conversion Constructors
- Conversion constructor is a constructor with one parameter
- Converts from one type of object to another
- Very similar to the copy constructor
Forcing explicit construction
- Providing a one-parameter constructor provides a conversion constructor
- Allows compiler to use it to convert to the type whenever it wants/needs to do so
- Use the keyword
explicit
Conversion Operators
- Convert from a class into something else
- Uses operator overloading syntax
- Instead of an operator symbol, the new type name and
()
are used
Friends
- Members can be private, protected or public
- Usually only class members can access private data
- Class can grant access to their
private
member data and functions to theirfriends
- The class still maintains control over which classes and functions have access
- The
friends
of a class are treated as class members for access purposes - although they are not members - Declare your friends within your class body and use the keyword
friend