0

I have two classes, Pony and Bear which inherits from an Animal Abstract Class.

I have made an Animal Array which contains one Pony and one Bear :

Animal **arr = new Animal * [2];
arr[0] = new Pony("pony name");
arr[1] = new Bear("bear name");

The argument to Pony and Bear is it name. I then want to print the Animal name by ovearloading the << operator. something like

cout << arr[0];  // Print something like : "I am Pony/Bear Name !"

But my test to overload fail... I try to do something like

ostream & operator<<(ostream& os, Animal &a);

But It do not detect the overload when I compile...

How is it possible to overload the << operator in my array of pointers ?

Full error after the test *arr[0]

main.cpp: In function ‘Object** MyUnitTests()’:
main.cpp:20:22: error: no match for ‘operator<<’ in ‘std::cout << * * obj’
main.cpp:20:22: note: candidates are:
In file included from /usr/include/c++/4.7/iostream:40:0,
             from Object.hh:14,
             from main.cpp:11:

And then 200 lines of errors comming from std::cout (they disapears if I remove the * on the arr[0]).

4
  • What is the type of arr[0]? Commented Jan 18, 2014 at 19:44
  • 1
    Its an array of pointers so cout << arr[0]; will print the pointer dir, jus try cout << *arr[0]; Commented Jan 18, 2014 at 19:45
  • Don't take a by non-const reference. If you're changing it, don't. Commented Jan 18, 2014 at 19:46
  • arr[0] is a pointer on a Pony Commented Jan 18, 2014 at 19:47

1 Answer 1

2

arr[0] is a pointer, so you'll need to perform indirection to be able to pass it to that operator<< overload:

cout << *arr[0];

You're using new much more than you should be. I'll let you off with the animals themselves because you need polymorphism (although you should use smart pointers instead), but the array of pointers does not need to be dynamically allocated:

Animal* arr[2];
Sign up to request clarification or add additional context in comments.

4 Comments

I have already try your code and it tells me no match for ‘operator<<’ in ‘std::cout << * * arr
@JérémyPouyet Looks like you have two asterisks there.
This message appears when I do cout << *arr[0]. What would your operator<< prototype ?
@JérémyPouyet Okay, I don't believe that the error matches the code you gave before. Can you give the source of main.cpp?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.