Is a special member function whose name is same as class name and preceded by?

While programming, the objects which hold certain data members and member functions have to be initialized before operating on them. This is usually done by member functions that initialize data members to predefined values. But there is a special member function in which the object initializes itself automatically when it is first constructed. This special member function is called a constructor.

Substantially, a constructor defines a value to data members of the class. A constructor is a special member function that is used to initialize objects of a class instantaneously when it is constructed.

Using and Declaring a Constructor

  • A constructor is a member function that has the same name as that of the class.
  • It is defined as any other member functions [both inside or outside] of the class.
  • Since a constructor just defines the value to a data member, there’s no return type to it.
  • They are called automatically when the objects are created.
  • They should be declared in the public section of the class.
  • Declaration Syntax: Consider the class name and constructor name to be demo. Let a and b be two integer variables.

class demo
	{
		private:
			int a,b;
		public:
			demo[]
				{
				a=1;
				b=2;
				}
	};

C++ program to demonstrate the use of a constructor

Consider the program to find the area of a circle. The name of the class will be demo. The two member functions will be declared, one for input and one for output. Since the name of the constructor should be the same as that of the class, the name of the constructor will also be demo. When the constructor demo is declared, the initialization of the class objects is done automatically.

#include 
#include
using namespace std;

class demo
{
  private:
     double radius, pi;
   public:
     void input[double r];
     double output[];
     demo[];
};

demo::demo[void]    //constructor definition outside the class
{
   pi=3.142;
}
void demo::input[double r]
{
  radius=r;
}
double demo::output[void]
{
  return [pi*radius*radius];
}

int main[]
{
  demo d1;

  d1.input[5.5];
  cout

Chủ Đề