Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Constructor and Attributes | Constructors and Destructors
C++ OOP

Constructor and AttributesConstructor and Attributes

One of the primary usage of the constructors is to initialize attributes of the class. A default constructor, for example, can be used to set initial values. For example:

cpp

main.cpp

If you don't specify value for name attribute of the object, it will be set to underfined as a default. You can try removing this constructor to see what changes occur.

Initializing Attributes with Constructor

Just as functions a constructor can accept parameters, allowing you to pass different arguments when instantiating an object. Also, constructor can be overrided, so you can increase flexibility, for instance varying number of arguments.

Click👇
cpp

main.cpp

Task

  • Create a constructor for the Location class that takes three parameters and initializes the instance variables with these values.
  • Output initialized attributes of the object to the console.

Everything was clear?

Section 2. Chapter 2
toggle bottom row

Constructor and AttributesConstructor and Attributes

One of the primary usage of the constructors is to initialize attributes of the class. A default constructor, for example, can be used to set initial values. For example:

cpp

main.cpp

If you don't specify value for name attribute of the object, it will be set to underfined as a default. You can try removing this constructor to see what changes occur.

Initializing Attributes with Constructor

Just as functions a constructor can accept parameters, allowing you to pass different arguments when instantiating an object. Also, constructor can be overrided, so you can increase flexibility, for instance varying number of arguments.

Click👇
cpp

main.cpp

Task

  • Create a constructor for the Location class that takes three parameters and initializes the instance variables with these values.
  • Output initialized attributes of the object to the console.

Everything was clear?

Section 2. Chapter 2
toggle bottom row
some-alt