c++printingshared-ptrvoid

how can I print a shared_ptr class?


How can I print a shared_ptr? I have to print sp1 and sp2 via void print(), but I have no clue how to do it.

This is the code:

struct MediaAsset
{
    virtual ~MediaAsset() = default; // make it polymorphic
};

struct Song : public MediaAsset
{
    std::string artist;
    std::string title;

    Song(const std::string& artist_, const std::string& title_) :
        artist{ artist_ }, title{ title_ }
    {
        std::cout << "Song " << artist_ << " - " << title_ << " constructed\n";
    }

    ~Song()
    {
        std::cout << "~Song " << artist << " - " << title << " destructed\n";
    }

    void print()
    {
        //Complete to show information about the current object
    }
};

using namespace std;

void example1()
{
    auto sp1 = make_shared<Song>("poets","carnival");
    shared_ptr<Song> sp2(new Song("poets","late goodbye") );
    sp1.print();
    sp2.print();
}

I wrote:

void print()
{
    std::cout << "artist " << artist << " - " << "title" << title << " end\n";
}

and this is the message I get when I run the program:

error: 'class std::shared_ptr<Song>' has no member named 'print'


Solution

  • The error message is correect. print() is not a method of shared_ptr itself. You need to dereference the shared_ptr to access the actual Song object, and then you can access its members as needed, eg:

    auto sp1 = make_shared<Song>("poets","carnival");
    shared_ptr<Song> sp2(new Song("poets","late goodbye") );
    sp1->print();
    sp2->print();
    

    Or:

    auto sp1 = make_shared<Song>("poets","carnival");
    shared_ptr<Song> sp2(new Song("poets","late goodbye") );
    (*sp1).print();
    (*sp2).print();