Hi all. I'm currently learning C++ from a tutorial C to C++. I have a question on references. More precisely, i'm confused why this code gives the following result.
result:
------------------------------------------------------
C:\Documents and Settings\Sebouh >C:\my_cpp_test s\cpp_test\debu g\cpp_test.exe
John, age 56
John, age 56
John, age 4212483 <----------------- WHY??
-----------------------------------------------------
why not Todd?
Thanks
Code:
#include <iostream> #include <cstring> using namespace std; class person { public: char *name; int age; person (char *n = "no name", int a = 0) { name = new char[100]; strcpy (name, n); age = a; } person (person &s) // The COPY CONSTRUCTOR { name = new char[100]; strcpy (name, s.name); age = s.age; } ~person () { delete [] name; } }; void foo(person p) { cout << p.name << ", age " << p.age << endl << endl; } person &bar() { return person("Todd", 15); } int main () { person k ("John", 56); cout << k.name << ", age " << k.age << endl << endl; foo(k); person m(k); person n = bar(); foo (n); return 0; }
------------------------------------------------------
C:\Documents and Settings\Sebouh >C:\my_cpp_test s\cpp_test\debu g\cpp_test.exe
John, age 56
John, age 56
John, age 4212483 <----------------- WHY??
-----------------------------------------------------
why not Todd?
Thanks
Comment