I have a problem, when executing the next initialization of a reference to an object in the file.h. In principle, the compiler does not show any kind of problem:
class Book{
public:
Author author2=Author("julio","[email protected]", 'm');
const Author &refAuthor=author2;
}
I also tried:
class Book{
public:
const Author &refAuthor=Author("julio","[email protected]", 'm');
}
But when I launch it in debug mode. After calling the print () method
cppDummy.refAuthor.print();
It shows me, what I attached to you in the image, it's as if the created Author object had not been assigned and had the empty attributes.
What am I doing wrong?
Author.cpp class
Author::Author(const string & name, const string & email, char gender) : name(name) {
setEmail(email); // Call setter to check for valid email
if (gender == 'm' || gender == 'f') {
this->gender = gender;
} else {
cout << "Invalid gender! Set to 'u' (unknown)." << endl;
this->gender = 'u';
}
}
void Author::setEmail(const string & email) {
// Check for valid email. Assume that a valid email contains
// a '@' that is not the first nor last character.
size_t atIndex = email.find('@');
if (atIndex != string::npos && atIndex != 0 && atIndex != email.length()-1) {
this->email = email;
} else {
cout << "Invalid email! Set to empty string." << endl;
this->email = "";
}
}