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

C++ paramters and pointers 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 *. 

    std::string::string (const char* s);

    There doesn't have to be a constructor for the array because arrays can be converted to pointers if that's available. 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(char x){ // constructor for chars

      std::cout << x;

     }

     A(const char* x){ // constructor for pointers, also works with arrays

        std::cout << x;

     }

     ~A(){

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

     }

    };

    void a(A a){ // the function takes an A

     std::cout << 'a';

    }

    void b(const A& a){ // the function takes an A

     std::cout << 'b';

    }

    int main() {

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

     b('B'); // calls the A constructor, outputs Bb bye

     a("Cstring"); // calls the A constructor, outputs Cstringa bye

    }

    (p.s. don't do the following

    const char str3[] = {'c','d'}; // an array of length 2

    f(str3); 

    because str3 is not null terminated it will go up the spout!

    )

    ( 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... )

    ( p.p.s.

    if you have done templates you can try another constructor

     template<int length>

     A(const char (&x)[length]){ // constructor for character array

         std::cout << x[length-2]; // display the last character in the string

     }

    then add to main:

    a("XYZ"); // a character array of length 4

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