OOP Lecture 5
OOP Lecture 5
In order to avoid that, a class can include a special function called its constructor, which
is automatically called whenever a new object of this class is created, allowing the class
to initialize member variables or allocate storage.
This constructor function is declared just like a regular member function, but with a
name that matches the class name and without any return type; not even void.
Constructors cannot be called explicitly as if they were regular member functions. They are only executed once,
when a new object of that class is created.
• It is always public.
• Constructors never return
• values, they simply initialize
• the object.
• Constructors can also take parameters
(just like regular functions), which can be
useful for setting initial values for attributes.
Just like functions.
Constructors can also be
defined outside the class. First, declare the
constructor inside the class, and then define it
outside of the class by specifying the name of
the class, followed by the scope resolution