David Faizulaev
David Faizulaev

Reputation: 5721

Overloading << operator in template linked list with inheritance

I'm trying to overload << operator within a template linked list.

in short I have one abstract class and 2 derived classes that inhered him. all 3 classes have operator << written & working well if I use dynamic_cast.

But when I try to use operator << within the template linked list I either get the address or a linker error for some reason.

Abstract class - Player

#ifndef PLAYER_H_
#define PLAYER_H_
#include <iostream>

class Player {
private:
  const char* m_name;
  int age;
public:
  static int numofPlayers;
  Player(const char*,int);
  virtual ~Player();
  friend std::ostream& operator<<(std::ostream& out, const Player &p);
};

std::ostream& operator<<(std::ostream& out, const Player &p);

#endif

One of the derived classes

class Goalkeeper:public Player {
private:
  int Saved_Goals;
  int Shirt_Number;
public:
  Goalkeeper(const char* name,int age, int number);
  ~Goalkeeper();

  friend std::ostream& operator<<(std::ostream& out, const Goalkeeper& s);
};

std::ostream& operator<<(std::ostream& out, const Goalkeeper& s);

Both of the << operators for base & derived work well! Only when I try to use them in the template linked list I get the address and not the data:

Template Linked List

template <typename T>
class Node {
  T* m_data;
  Node* next;
public:
  Node ();
  Node(T*, Node<T>*);
  ~Node();
  T* getData ()const {return this->m_data;};
  Node* getNext()const{return this->next;};
  template <typename T>
  friend std::ostream& operator<<(std::ostream &output, const Node<T>& Nd );
};

template <typename T>
std::ostream &operator << (std::ostream &output,const Node<T>& Nd ) {
  output<<Nd.m_data<<endl;
  return output;
}

template <typename T>
void List<T>::PrintMe() const {
  Node<T>* temp=this->head;
  while(temp) {
    cout<<*temp;
    temp=temp->getNext();
  }
}

Upvotes: 1

Views: 1202

Answers (1)

Csq
Csq

Reputation: 5855

You are printing out the pointer. Use the dereference operator to print out the value.

output<<*(Nd.m_data)<<endl;

Also please indent your code before posting!

Question in comment:

It prints the data now but only for the base class and not the derived class for some reason

Because method overloading is based on the static type of an expression. Therefore with a List<Base>, the method called is operator<<(ostream&, const Base&). Try a List<Derived> and your code will work! You'll need a virtual function call that does the work for you in the operator<< of the base class to make a list containing both kind of elements work.

Upvotes: 3

Related Questions