C++ Class Structure and Object Lifecycle Management
Sections of a C++ Class
- Private Section: Only member functions can access the class member functions; descendant classes are denied access to the private members of a class.
- Protected Section: Only member functions of a class and its descendant classes' members can access these members.
- Public Section: Specified members are visible to all member functions and external calls to the class.
Rules for Class Sections
- Sections of the class can appear more than once in any order.
- If no section is specified, C++ treats members as private by default.
- Grouping data members in the public section should be avoided unless such a declaration significantly simplifies the design. Data members are usually placed in the protected section to allow access for descendant classes.
Ways to Create an Object
Objects can be created by declaring a global object, declaring a local or temporary object, invoking the new operator, or by explicitly calling a constructor.
Types of Constructors
Default Constructor
class();
When no constructor is specified in a class, the compiler creates one by default. If a global object is created, the constructor initializes numeric data members to zero and alphanumeric members to null by default. If the object is initialized with local values, they are considered indeterminate (garbage).
Explicit Constructor with Arguments
class(arguments);
A value must be specified following the declaration of the object.
Explicit Constructor with Default Arguments
class(arguments_initialized);
A way to reduce the number of builders is by using constructors with default arguments.
Copy Constructor
class::class(const class &initial_object);
Another way to create an object is from another object by assigning a different name at the time of its declaration.
Explicit Constructor via Assignment
Another way to initialize an object is by assigning another object of the same class at the time of the declaration.
The New Operator
The new operator can allocate memory for an object or an array of objects. It assigns memory from the free store (heap) and returns a pointer to an object of the specified type that refers to that space.
Object Destructors
A destructor is a function that allows each constructed object to be destroyed, freeing the memory it occupies. An object is destroyed when leaving the scope in which it was built.
Destructor: It is a special member function of a class that is used to remove an object of that class, releasing it from its memory addresses.
The 'this' Pointer
The this pointer is a pointer that is passed to any automatic member function when it is invoked. It is a pointer that the function receives automatically, referring to the object itself.