Search code examples
c++default-parameters

How to pass a string as default argument in C++


How can I properly pass a const string, for example: "Hello" as a default parameter to a constructor without getting any warnings and errors? In other words how can I preserve memory for them before the function is called?


Solution

  • #include <iostream>
    
    const char *defString = "Hello";
    void foo(const char *str = defString) {
        std::cout << str;
    }
    
    int main() {
        foo();
        foo("Hello, world!\n");
    }