Course Content
C++ OOP
C++ OOP
What is a Constructor of the Class
Constructor is a special method of a class that is called when an object is created. With it you can initialize the attributes to meaningful values.
By using constructors, you can simplify the creation of objects. Without a constructor, you would have to set each property individually and might need to call multiple methods just to get the object into a usable state.
The primary purpose of a constructor is to initialize the newly created instance. It can set the initial values of the attributes based on the parameters passed to the constructor, ensuring the object starts in a valid state.
Syntax of Constructor
While the process of developing a constructor might appear straightforward, it involves numerous specific considerations. The general approach to creating one is:
student
class Student { public: Student() { name = 'Default'; } std::string name; };
Name: constructor has the same name as the class itself;
Return type: constructors do not have a return type, not even
void
;Parameters: constructors can take parameters and can be overloaded with different sets of parameters to allow various ways of initializing objects;
Automatic Invocation: constructor is called automatically by the compiler when an object is created.
Default Constructor
A default constructor is a constructor that can be invoked without any arguments. Here's how default constructors are defined and used:
main
#include <iostream> class Example { public: Example() { std::cout << "Object was created!"; } }; int main() { Example obj; }
You can experiment with a code above. The logic written in the Example() method is executed every time an instance of the class is created.
Try to add one more object or change the logic inside the constructor.
If no constructor is defined, the compiler generates a default one. Its behavior depends on the member variable types: fundamental types, default-constructible types, or user-defined types.
main
#include <iostream> class Example { public: int value; }; int main() { Example obj; // Default constructor std::cout << obj.value; }
An attribute is a fundamental data type. The automatically generated default constructor does not initialize built-in-type member variables. They will have indeterminate values if you create an object and do not explicitly initialize these fields.
You might find that compiler provide a consistent value for value variable, but the standard doesn't require it and it is possible that it will contain a garbage value.
Thanks for your feedback!