Type enforcement to map a type of value to another type of value, and this mapping between the type is specified when the type is defined. Mandatory characteristics of the type of constructor:
Set T-class has the following form of constructor:
T :: t (u)
T :: T (const u &)
This constructor creates a T type object that is initialized using the value of the U type. When a T type operand is required in an expression, the programmer provides a U type operand, and the compiler can automatically use this constructor to create a T type operand by the U type operand, so, This form of constructor has a type forced effect. E.g:
File: //myclass.h
#include
Class myclass
{public:
Myclass (int i = 0);
Void Print () const;
~ Myclass ();
Private:
Int m;
}
FILE: //myclass.cpp
#include "myclass.h"
Myclass :: MyClass (INT I)
{m = i;
COUT << "Constructor Called." << m << endl;
Void myclass :: print () const
{COUT << m << endl;}
Myclass :: ~ myclass ()
{COUT << "Destructor Called." << m << endl;}
Investigate the following procedures now. In this program, the function fun () has a reference parameter, but when the function fun is called, the real parameters used are not a similar type of left value.
#include
#include "myclass.h"
Void Fun (const myclass & c);
int main ()
{Fun (5);
Return 0;}
Void Fun (Const myclass & c)
{c, print ();
The result of the program is:
Construct caled. 5
5
DESTRUCT CALLED. 5
The function fun () uses the reference parameters of the base type to myclass, which requires its caller to provide an operand with MyClass when calling the function, but in our program, the type of arguments is int, so the compiler The generated code is enforced, the mandatory result is an anonymous object of a MyClass type in the main () function (forced environment), and the metall parameter c is referenced to the anonymous object.