I am trying to learn by experimenting with constructors and references. I wrote the class as follows and I expect the answer written after the class
#include <iostream>
#include <string>
class human {
public:
const std::string& m_name;
void printit() {
std::cout <<"printit "<< m_name << std::endl;
}
human(const std::string& x):m_name(x){
std::cout << "the constructor "<< m_name << std::endl;
}
~human() {
std::cout << "dest called"<< std::endl;
}
};
int main()
{
human x("BOB")
x.printit();
return (0);
}
> the constructor BOB
> printit BOB
> dest called
However I get something like this. m_name
is lost when I call the function. The same class works fine when using int
in place of string
. What is the problem?
> the constructor BOB
> printit
> dest called
Now the same class with int const
reference
#include <iostream>
class human {
public:
const int& m_name;
void printit() {
std::cout <<"printit "<< m_name << std::endl;
}
human(const int& x):m_name(x){
std::cout << "the constructor "<< m_name << std::endl;
}
~human() {
std::cout << "dest called"<< std::endl;
}
};
int main()
{
human x(3);
x.printit();
return (0);
}
I get the correct answer in this case.
> the constructor 3
> printit 3
> dest called
Can someone explain the reason? Do builtin types persist?