Reputation: 77
I have two classes an "Author" and a "Book" class. The book class constructor uses the Author constructor. The problem that is happening is that when I change a value in the author class using a setter function and then I try using the Book print function to print all the information, the new value is not printed.
I set the default constructor of Author to implement all private value.
//Author class
Author::Author(string name, string email, char gender)
{
this->name = name;
this->email = email;
this->gender = gender;
}
Author::Author()
{
}
Author::~Author()
{
}
string Author::getEmail()
{
return email;
}
void Author::setEmail(string email)
{
this->email = email;
}
string Author::print()
{
return name + " (" + gender + ") @ " + this->email;
}
//Book class
Book::Book(string name, Author author, double price)
{
this->author = author;
this->name = name;
this->price = price;
}
Book::Book()
{
}
Book::~Book()
{
}
Author Book::getAuthor()
{
return this->author;
}
string Book::print()
{
return name + " by " + this->author.print();
}
//Main class
int main()
{
Author author("Jonathan Gonzalez", "g.jonathan.com",'M');
Book stock("NO BS! THE REALITY OF THE STOCK MARKET", author, 4.99);
cout << author.print() << "\n" << endl;
cout << stock.print() << "\n" << endl;
author.setEmail("[email protected]");
stock.setPrice(2.99);
cout << stock.print() << "\n" << endl;
return 0;
}
When I use the stock.print() function after I have changed a value using the author.setEmail() function it does not print using the new email.
OUTPUT Jonathan Gonzalez (M) @ g.jonathan.com
NO BS! THE REALITY OF THE STOCK MARKET by Jonathan Gonzalez (M) @ g.jonathan.com
NO BS! THE REALITY OF THE STOCK MARKET by Jonathan Gonzalez (M) @ g.jonathan.com
// //Expected OUTPUT
Jonathan Gonzalez (M) @ g.jonathan.com
NO BS! THE REALITY OF THE STOCK MARKET by Jonathan Gonzalez (M) @ g.jonathan.com
NO BS! THE REALITY OF THE STOCK MARKET by Jonathan Gonzalez (M) @ [email protected]
Upvotes: 1
Views: 63
Reputation: 206567
When I use the stock.print() function after I have changed a value using the author.setEmail() function it does not print using the new email.
That's because stock
has its own copy of the Author
object. Changing the state of the author
object in main
does not change the state of stock.author
, the Author
object in stock
.
I would recommend adding a member function to Book
to set the Author
.
void Book::setAuthor(Author const& author)
{
return this->author = author;
}
In main
, call the function.
author.setEmail("[email protected]");
stock.setAuthor(author); // Add this
stock.setPrice(2.99);
Now, the call to print will work as per your expectation.
cout << stock.print() << "\n" << endl;
Upvotes: 3
Reputation: 27011
You should make Author
inside Book
class as a pointer.
class Book
{
Author* author;
Book(string name, Author* author, double price)
{
this->author = author;
}
}
Then pass the address
Book stock("...", &author, 4.99);
Upvotes: 0