A constructor in C++ is a special method
that is automatically called when an object of a class is created.
The constructor has the same name as the class, it is always public, and it does not have any return value.
To create a constructor, use the same name as the class,
followed by parentheses ()
Parameters in Constructors:-
Constructors can also take parameters (just like regular functions),
which can be useful for setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with different parameters.
Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc).
When we call the constructor (by creating an object of the class), we pass parameters to the constructor,
which will set the value of the corresponding attributes to the same
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 :: operator,
followed by the name of the constructor (which is the same as the class)
We are now familiar with the 'public' keyword
The public keyword is an access specifier. Access specifiers define how the members
(attributes and methods) of a class can be accessed.
In the example above, the members are public -
which means that they can be accessed and modified from outside the code.
However, what if we want members to be private and hidden from the outside world?
In C++, there are three access specifiers:
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from outside the class
protected - members cannot be accessed from outside the class, however,
they can be accessed in inherited classes. You will learn more about Inheritance later.
By default, all members of a class are private if you don't specify an access specifier