Thread: need help!

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    14

    need help!

    I don't understand what does "the constructor is called implicitly by C++" means.
    I mean what is different between calling implicitly or explicitly?
    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    My guess is that it means that say:
    Code:
    A a; // Invoke the default constructor to instantiate an A object named a.
    Invokes the default constructor for class A even though it does not look like a function call, as opposed to explicitly calling the constructor with:
    Code:
    a.A(); // Imaginary syntax for an explicit constructor call for class A.
    Then there are other circumstances where invoking the constructor looks a little like a function call because of the parentheses, but otherwise is not proper function call syntax.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    "the constructor is called implicitly by C++"
    That's a poor way to phrase it. A Constructor is called intentionally, whether you've coded one up or not, when a object is instantiated. There's the default constructor that you don't have to code, or you can code one up to do additional stuff.

    So, perhaps it should say "the Constructor is automatically called by C++ when an instance is created" or something like that.

    Todd

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    The explicit keyword can be used on constructors to force explicit use of the constructor. For example:
    Code:
    class Data_Implicit
    {
    public:
      Data_Implicit(int data) : data_(data) { }
      int data_;
    };
    
    class Data_Explicit
    {
    public:
      explicit Data_Explicit(int data) : data_(data) { }
      int data_;
    };
    
    void FooImplicit(Data_Implicit di)
    {
      std::cout << di.data_;
    }
    
    void FooExplicit(Data_Explicit de)
    {
      std::cout << de.data_;
    }
    
    int main()
    {
      FooImplicit(3);
    
      FooExplicit(3); // compiler error... trying to call explicit constructor implicitly
      FooExplicit(Data_Explicit(3)); // ok explicit call to constructor made.
    }

Popular pages Recent additions subscribe to a feed