Search code examples
c++oopdefault-constructor

I dont understand how to pass and retrieve variables from method in one class to other method in other class


I am working on OOP C++ program and I'm bit struggling. I'm trying to create a program that demonstrates use of default and non-default constructors and pointers. I'm trying to do default constructor first.

So I am able to store and retrieve only the local variables inside of one method. But now I must pass values to other class (I think I must) and then retrieve the information again but little modified.

I could initialize object to one class as I did but then when I try to retrieve the object it basically doesn't retrieve anything but empty space. How do I correctly pass an object to method in another class and then retrieve it back?

Any pointers?

Book.cpp

#include <iostream>
#include <sstream>
using namespace std;

#include "Book.h"

Book::Book()
{
}

void Book::setTitle(string  title)
{
    this->title = title;
}

void Book::setAuthorName(string first, string last)
{
    Author author;

    author.setFirstName(first);
    author.setLastName(last);
}


void Book::setPrice(double price)
{
    this->price = price;
}

string Book::convertDoubleToString(double number)
{
    return static_cast<ostringstream*>( &(ostringstream() << number) ) -> str();
}

string Book::getBookInfo()
{
    stringstream ss;
    Author author;

    ss << title << endl << author.getFullName() << endl << "$" << convertDoubleToString(price) << endl;

    return ss.str();
}

Solution

  • This part is not going to work

    void Book::setAuthorName(string first, string last)
    {
        Author author;
    
        author.setFirstName(first);
        author.setLastName(last);
    }
    

    because inside this function you create a local object, set its values and then its destroyed when the function exits. You need to create a member variable of class Author inside your Book class if you want to retain this author information.

    Inside your Book class declaration, you need something like this

    class Book {
        Author m_Author;  // This is your member variable that you can store author data in
    
    };
    

    then inside your setAuthorName function, set the values of m_Author rather than creating a local variable. This will retain the values inside the member variable m_Author