A Constructor has the Following Characteristics

By
Last updated:

A constructor is a special member function whose main operation is to allocate the required resources such as memory and initialize the object of its class.

The constructor of a class is the first member function to be executed automatically when an object of the class is created.

Syntax
class classname
{
Public:
classname ( ); // Constructor Prototype
};
classname :: classname ()
{
// Constructor body definition
}

Similar to other members, the constructor can be defined either within, or outside the body of a class. It can access any data member like all other member functions but cannot be invoked explicitly and must have public status to serve its purpose. The constructor which does not take arguments explicitly is called default constructor.

A constructor has the following characteristics

  • It has the same name as that of the class to which it belongs.
  • It is executed automatically whenever the class is instantiated.
  • It does not have any return type.
  • It is normally used to initialize the data members of a class.
  • An object with a const cannot be used as a member of a union.
  • It also used to allocate resources such as memory to the dynamic data members of a class.
  • They make implicit calls to the operators to the operators new and delete when memory allocation is read.
  • It should have public access within the class.
  • It cannot be declared as as static or const.
  • Constructor cannot be virtual.
  • They cannot be inherited, through the derived class can call the base class const.

//Constructors

#include<iostream.h>
class sample
{
int a;
Public:
sample();
void show()
{
cout<<a; }
};
samplw :: sample()
{
cout<<"\n This is a constructor";
a=100;
}
main ()
{
sample S;
S.show ();
}
Output

This is a constructor 100.

Read More Topics
Static member function in C++
Error handling file I/O in C++
Pointer to pointer in C++
Pointers and arrays in C++

Santhakumar Raja

Hello The goal of this blog is to keep students informed about developments in the field of education. encourages pupils to improve as writers and readers.

For Feedback - techactive6@gmail.com

Leave a Comment