Search code examples
c++pointersreferenceoperator-overloadingabstract-class

Overloading ostream << operator with pointer as parameter resulting with memory adress on output


I have some trouble with overloading ostream operator. There are 3 classes, abstract base class Packet another abstract class Sequence which inherits from Packet and class TimeHistory which inherits from Sequence.

class Packet
{
//some stuff
};

template <typename T = double>
class Sequence : public Packet
{
std::vector<T> buffer;
//some other stuff
}

template <typename T = double>
class TimeHistory : public Sequence<T>
{
template <typename X>
    friend std::ostream &operator<<(std::ostream &out, Packet *A);
//another stuff
}

And a friend function to print data in the objects

std::ostream &operator<<(std::ostream &out, Packet *A)
{
    TimeHistory<T> *th = dynamic_cast<TimeHistory<T> *>(A);
    out << th->device
        << th->description
        << th->channelNr;
    for (auto in : th->buffer)
        out << in << std::endl;
    return out;
} 

When I make an instance of the class like:

std::unique_ptr<Packet> channel1 = std::make_unique<TimeHistory<double>>(/*some constructor stuff*/);

and call the function

  std::cout<<(channel1.get());

I get only a memory cell adress at the output: 0x560c8e4f1eb0 Could someone point what am I doing wrong?


Solution

  • std::unique_ptr::get will return a pointer to the managed object. If you want to get a reference to managed value use

    std::cout<< *channel1;
    

    To overload operator<< for an abstract class you can use a reference instead of a pointer:

    friend std::ostream &operator<<(std::ostream &out, Packet &A);