Purpose of explicit keyword - Constructor and Destructor

Q.  The purpose of explicit keyword is to tell the compiler that a certain constructor may not be used to implicitly cast an expression to its class type.
- Published on 19 Jul 15

a. True
b. False

ANSWER: True
 

    Discussion

  • Raj   -Posted on 08 Oct 15
    Yes The purpose of explicit keyword is to tell the compiler that a certain constructor may not be used to implicitly cast an expression to its class type.
    class Dimention
    {
    private:
    int length

    public:
    Dimention(int x)
    {
    length=x;
    cout< }


    };
    int main()
    {
    Dimention d=10; //implicit conversion.

    return 0;
    }

    In the above example Dimention d=10; is an implicit conversion type int to type Dimention. If you want that it should not be happen then you should use keyword explicit to the constructor.
    explicit Dimention(int x)
    {
    length=x;
    cout< }
    Now you cannot write Dimention d=10; It will give compile time error. Now, only constructors of the form Dimention d(10) will be allowed.

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)