need help!

This is a discussion on need help! within the C++ Programming forums, part of the General Programming Boards category; I don't understand what does "the constructor is called implicitly by C++" means. I mean what is different between calling ...

  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
    21,588
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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
    Katy, Texas
    Posts
    2,309
    "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,317
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21