Explicit Call to a Constructor

前端 未结 5 1836
萌比男神i
萌比男神i 2021-02-04 16:16

I know the concept that we can call the Constructor both Explicitly and Implicitly, and i have tested both the scenarios(generally till now my all purp

5条回答
  •  攒了一身酷
    2021-02-04 16:53

    There are three ways a constructor can be called:

    • Implicitly, by declaring an instance of the type without initializing it
    • Also implicitly, by either initializing an instance with = or by causing an implicit conversion from the argument type to your class.
    • Explicitly calling the constructor, passing arguments.

    Which of these you can use in a particular context depends on the constructors you're calling.

    class Foo 
    {
        Foo();                                  // 1
        Foo(int a);                             // 2
        explicit foo(const std::string& f);     // 3
        Foo(int c, int d);                      // 4
    };
    
    1. This constructor will be called implicitly when declaring Foo f;. Never attempt to call a constructor without arguments explicitly, as Foo f(); will declare a function!
    2. This one can be called by writing Foo f = 42; or Foo f(42).
    3. The explicit keyword forbids implicit conversion by writing Foo f = std::string("abc"); or function_taking_foo(function_returning_string());.
    4. As there are multiple arguments, the explicit version is the only suitable.

提交回复
热议问题