Hello! I am a pythonist, but out of decency I decided to care with ++. Task: there is a class Foo with a private constructor. There is a function foo_says which uses the public method of the class Foo . We need to write a function get_foo , thanks to which it will be compiled:
foo_says(get_foo("Hello!")); Code:
#include <iostream> #include <stdio.h> #include <cstddef> // size_t #include <cstring> // strlen, strcpy using namespace std; struct Foo { void say() const { std::cout << "Foo says: " << msg << "\n"; } protected: Foo(const char *msg) : msg(msg) { } private: const char *msg; }; struct Fo : Foo { Fo(const char* msg) : Foo(msg) { } }; void foo_says(const Foo &foo) { foo.say(); } const Foo& get_foo(const char *msg) { const Fo F(msg); const Foo& f = F; return f;; } int main() { foo_says(get_foo("Hello!")); return 0; } Solution and problem: Since the task is from the section "Class Inheritance", I inherited Fo , which will create an object, and then it can be brought (truncated) to the Foo object. But instead of the Hello line, I get . . I suspect that after exiting some function, the pointer to Hello is deleted, because "Foo says" is displayed correctly. Then where is this happening - I can not understand?