x

C++ Constructors

PREV     NEXT

C++ Constructors:


What are constructors?

  • The constructor is a member function of a class which initialized the objects of a class. The constructor will be called automatically when an object is created.
  • The constructor has the same name as of the class and it does not have any return type.

How the constructors are different from a member function?

The constructors are different from the member function in such ways like:

  • Constructor can be called automatically when an object is created.
  • The constructor name is same as of the class.
  • It does not have the return type.
  • If the constructor is not specified than the compiler will generate a default constructor.

Types of Constructors

There are two types of constructors:

  • Default Constructor
  • Parameterized Constructor

Default Constructor:

The default constructor is the constructor which does not accept any argument. It does not have any parameters.


Let us understand this through an example:

Parameterized Constructor:

  • In the parameterized constructor we can pass the arguments to the constructor. The arguments will help to initialize an object when it is created.
  • Define the constructor’s body then the parameters are used to initialize the object.

Let us have a look at the example:

What are the uses of Parameterized Constructor?

  • They are used to initialize the various data elements of different objects with different values when they are created.
  • This constructor is used to overload constructors.

PREV     NEXT



Like it? Please Spread the word!