website logo

Constructors in c++

constructors in c++ is a special member function that's mainly use to initialize the object of class. name of constructor will be same as class name and invoked whenever object of class is created. whenever object of any class will create that's class constructors will invoked and initialize the member variable of associated object.


Constructors declaration and definition

class constfloat{
float k; // member variable
float m;
public:
constfloat(void); // declaration of constructor
};

constfloat :: constfloat(void) // definition of constructor
{
k=5.4;
m=6.7;
}

Whenever we create object of class constfloat constructor constfloat will be invoked and initialize member variable k and m with k=5.4 and m=6.7.
For example if we create object of class constfloat like

constfloat obj1;

object obj1 created here and initialize data member k=5.4 and m=6.7
then only object of class constfloat is not created object creation and initialization of object both done on same line.

constructors that written without parameter is known as default constructor and constructor that's accept parameter is known as parameterized constructors.
if there is not any constructors defined in class then compiler provides default constructor to initialize object of that class and default constructor never contain any parameters.

Some important point about constructors
1) constructors never return value so constructors do not have return statment.
2) constructors should be declared in the public section of class.
3) constructors can not be inherited.
4) constructors can not be virtual.

Parameterized constructors

Parameterized constructors is a constructor that accept parameter and initialize object through that parameters value.

Example
class constfloat{
float k; // member variable
float m;
public:
constfloat(float a , float b); // declaration of Parameterized constructor
};

constfloat :: constfloat(float a , float b) // definition of constructor
{
k=a; //initialize through parameters
m=b;
}

whenever we create object of class constfloat we must pass initial value of data members as a arguments for object initialization. we pass arguments by calling constructor explicitly or implicitly.

constructor calling explicitly
constfloat obj1 = constfloat(2.4,5.6); // explicit call

constructor calling implicitly
constfloat obj1(2.4,5.6); // implicit call