Does a const reference class member prolong the life of a temporary?

Why does this: #include <string> #include <iostream> using namespace std; class Sandbox { public: Sandbox(const string& n) : member(n) {} const string& member; }; int main() { Sandbox sandbox(string(“four”)); cout << “The answer is: ” << sandbox.member << endl; return 0; } Give output of: The answer is: Instead of: The answer is: four 6 … Read more

What is this weird colon-member (” : “) syntax in the constructor?

Recently I’ve seen an example like the following: #include <iostream> class Foo { public: int bar; Foo(int num): bar(num) {}; }; int main(void) { std::cout << Foo(42).bar << std::endl; return 0; } What does this strange : bar(num) mean? It somehow seems to initialize the member variable but I’ve never seen this syntax before. It … Read more