Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 month ago

c++ question?

static int f(const std::string& s) { return s.length(); }

    void g() {

      const char* str1 = "hello";

      f(str1); //@1

      const char str2[] = "world";

      f(str2); //@2

    }

Explain exactly why the calls @1 and @2 work. Specifically, explain how the actual arguments to f() in each call are passed over to the formal parameter s in f(). Don't understand

1 Answer

Relevance
  • 1 month ago
    Favorite Answer

    std::string has a constructor for const char *. There doesn't have to be a constructor for the array because arrays are converted to pointers. A term often used is that they "decay" to pointers.

    So a temporary object is constructed when the const char* is passed to a function which takes a string or a const reference to a string. The temporary object is kept on the stack until the function returns then it is deleted.

    You can make your own classes do the same, so the constructor for class A gets called even though no A objects are made explicitly:-

    #include <iostream>

    class A {

    public:

     A(int x){

      std::cout << x;

     }

     ~A(){

      std::cout << " bye\n";

     }

    };

    void a(A a){

     std::cout << 'a';

    }

    void b(const A& a){

     std::cout << 'b';

    }

    int main() {

     a(1); // calls the A constructor, outputs 1a bye

     b(2); // calls the A constructor, outputs 2b bye

    }

    (p.s. if you don't want this to happen you can put the keyword 'explicit' in front of the constructor being used 

    https://en.cppreference.com/w/cpp/language/explici... )

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.