6. Classes, Constructors & inline functions
21/02/23
new & delete
- Same kind of problems occur with
new
anddelete
withmalloc()
andfree()
Classes and structs
- In C++ you can add functions to
structs
, use inheritance etc - Do not treat them like C items
- Implementing some of these features may require that some hidden data is created
- Only thing difference is encapsulation,
struct
is public,class
is private - Good C++ practises
- Data only and no member function: use a struct. You get the guarantees about size and positions of member data that you get in a C
struct
- If you add member functions then use a
class
- Data only and no member function: use a struct. You get the guarantees about size and positions of member data that you get in a C
- Data and methods in class are either
private
orpublic
- Interface methods can be:
- Mutators - Change the 'state' of the object
- Accessors - Only query values, no changes
Constructors and Destructors
- Constructor - Called when an object is created
- Created on the stack, when new is used
- Destructor - Called when an object is destroyed
- When objects on stack are destroyed. When delete is used to destroy an object
malloc
andfree
do not create objects
Default Constructor
- Constructor which can be called with no parameters or has default values for all parameters
- Used whenever no parameters are specified
Initialisation lists are used a LOT in C++
Inline functions & Member functions and data
- Act exactly line normal function but no function call is made
- Useful for small fast one time functions