automatic constructor defaulting

This is a discussion on automatic constructor defaulting within the C++ Programming forums, part of the General Programming Boards category; Hello, I just came across this "feature" in c++: Code: class Blah{ public: Blah() {}; Blah(const string& thestr) {}; Blah(const ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    108

    automatic constructor defaulting

    Hello,

    I just came across this "feature" in c++:

    Code:
    class Blah{
       public:
          Blah() {};
          Blah(const string& thestr) {};
          Blah(const char* mwah) {}
    };
    
    void moo(const Blah& theblah){
       // do nothing
    }
    
    int main(){
    
       moo(Blah());
    
       moo("haha");
    
       moo(string("haha"));
    
    }
    So obviously moo only should be taking a Blah class, but somehow it can also take a char* and a string? What is this feature called? I'm just making sure this is standard c++..

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,990
    This is in the realm of standard C++. A temporary is created in each case, and the const reference parameter can bind to this temporary. If you wish to prevent this implicit conversion, declare the respective constructors as explicit, e.g.,
    Code:
    explicit Blah(const string& thestr) {}
    explicit Blah(const char* mwah) {}
    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
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    Hmm. Interesting. Learned something new here. So that's why functions expecting a std::string can be thrown a "const char *", too.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    108
    Yeah, I think this would be useful as a way to lazily implement overloading.. heh

    thanks laserlight

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why automatic variables are assigned with garbage values
    By srinivasg in forum C Programming
    Replies: 1
    Last Post: 11-08-2005, 06:14 AM
  2. automatic variables
    By FOOTOO in forum C Programming
    Replies: 5
    Last Post: 03-08-2005, 05:30 PM
  3. Automatic vs. Static Duration
    By JMB in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2002, 07:16 PM
  4. Automatic Time in C++Builder ??
    By Gugge in forum Windows Programming
    Replies: 0
    Last Post: 06-18-2002, 12:58 PM
  5. Automatic <cr> in User Inteface
    By chubaka in forum C Programming
    Replies: 3
    Last Post: 01-14-2002, 12:06 PM

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