Use of std::ostream for Printing Vectors - c++

I'm quite new to C++ and I am trying to print out a vector of Institutions, which is a type of object that I created. The creation of the object and the rest of my program runs just fine but when I try to print out the vector, the "<<" gives an error that says "operand types are std::ostream".
void PrintVector(const vector<Institution> &institutions)
{
for (int x = 0; x < institutions.size; x++)
{
cout << institutions.at(x) << endl;
}
}
I've tried to do research on what std::ostream is or what it does but since I don't know a lot about C++ (or programming in general), I can't understand any of the sites that explain it. Why won't the usual "cout <<" work in this situation? Can anybody explain to me what this means or if there is a different way to print out my vector that doesn't require this?
Any help is appreciated, thanks.

You may want to overload the ostream operator (<<) for your class Institution:
https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
ostream& operator<<(ostream& os, const Institution& inst)
{
os << inst.foo; /* some member variable */;
return os;
}

The problem is that a C++ ostream (which cout is) does not have any way to print out an Institution object. You are going to have to overload the operator<< function in our Institution as described in the link posted in the other answer (https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx?f=255&MSPPError=-2147217396) in order to get it to work.

You have to provide an operator << for your class:
std::ostream& operator << (std::ostream& os, const Institution& institution)
{
os << institution.getValue();
// ...
return os;
}

operator<< is overloaded to allow outputting built-in types like int and double. But you'll need to tell the compiler how to output your class Institution by overloading it again:
std::ostream& operator<<(std::ostream& os, const Institution& inst) {
os << inst.name(); // or something
return os;
}

There are at least two problems with the code that you have shown.
1)
for (int x = 0; x < institutions.size; x++)
std::vector::size() is a class method, a function. It is not a class member. This should read:
for (int x = 0; x < institutions.size(); x++)
2)
cout << institutions.at(x) << endl;
Unfortunately, std::ostream knows nothing about your Institution class. You will need to implement a class method, such as display(), that will assemble a printable representation of the contents of the class, and write it to the output stream. So, for example, if the class contains two std::strings, called name, and address:
class Institution {
// ...
public:
void display(std::ostream &o)
{
o << name << std::endl << address << std::endl;
}
// ...
};
... or, in whatever formatting style you want your class instances to be displayed. Then:
for (int x = 0; x < institutions.size(); x++)
institutions.at(x).display(std::cout);
3)
Well, here's a bonus problem with your code. It is actually written in an obsolete C++ dialect that went out of style decades ago. Whatever textbook you're using to learn C++, you need to ditch it, and pick up a textbook that was written this century, and which will teach you modern C++. In modern C++, this becomes a much more readable:
for (const auto &institution:institutions)
institution.display(std::cout);

The answers here are all correct. I will provide a slightly different answer to the displaying issue, as this is a recurring problem. What you can do is define an abstract class, we'll call it IDisplay, which declares a pure virtual function std::ostream& display(std::ostream&) const and declares operator<< as a friend. Then every class that you want to be display-able must inherit from IDisplay and consequently implement the display member function. This approach reuses the code and is pretty elegant. Example below:
#include <iostream>
class IDisplay
{
private:
/**
* \brief Must be overridden by all derived classes
*
* The actual stream extraction processing is performed by the overriden
* member function in the derived class. This function is automatically
* invoked by friend inline std::ostream& operator<<(std::ostream& os,
* const IDisplay& rhs).
*/
virtual std::ostream& display(std::ostream& os) const = 0;
public:
/**
* \brief Default virtual destructor
*/
virtual ~IDisplay() = default;
/**
* \brief Overloads the extraction operator
*
* Delegates the work to the virtual function IDisplay::display()
*/
friend inline
std::ostream& operator<<(std::ostream& os, const IDisplay& rhs)
{
return rhs.display(os);
}
}; /* class IDisplay */
class Foo: public IDisplay
{
public:
std::ostream& display(std::ostream& os) const override
{
return os << "Foo";
}
};
class Bar: public IDisplay
{
public:
std::ostream& display(std::ostream& os) const override
{
return os << "Bar";
}
};
int main()
{
Foo foo;
Bar bar;
std::cout << foo << " " << bar;
}
Live on Coliru

Related

Templates Objects and Primitives

I have the following class template which will accept both primitives and object. However like this I can only print primitives. How can I make it function using both primitives and objects? Thanks
template<class T>
class A
{
private:
vector <T> l;
public:
void print() const
{
for (int i=0;i<.size();i++)
{
cout<<l[i]<<endl; //error here
}
}
};
The reason why you can print primitives is that <iostream> provides overloads for operator<< for them.
To let your template print your classes in the same way, you need to define your own implementation of the operator:
// This implementation puts operator << outside your class.
// Mark it "friend" in MyClass if it needs access to private members of MyClass.
ostream& operator<<(ostream& ostr, const MyClass& myClass) {
// Do the printing based on the members of your class
ostr << myClass.member1 << ":" << myClass.member2;
return ostr;
}
The compiler will detect this operator during template expansion, and use it for printing when you do this:
cout<<l[i]<<endl;
You can put operator<< inside your class as well:
ostream &operator<<(ostream &os) {
ostr << member1 << ":" << member2;
}
I am assuming that here, you want to print an object instead of a variable belonging to a fundamental datatype.
For such cases, you can look at operator overloading in C++(more specifically overloading insertion operator).
For more information about overloading the insertion operator for an object, you can visit this URL
http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
Given below is an example about how to go about it
ostream& operator<<(ostream& os, const Datatype& dt)
{
os << dt.a <<" " << dt.b;
return os;
}
Here Datatype is the name of the class and a and b are two private members of a and b which will be printed when you try to print the object.
However, to overload using this technique, do not forget to make this function as a friend function of the class(as given below) as the function requires access the to private members of the class.
friend ostream& operator<<(ostream& os, const Datatype& dt);

Override operator using class method in c++ [duplicate]

That's basically the question, is there a "right" way to implement operator<< ?
Reading this I can see that something like:
friend bool operator<<(obj const& lhs, obj const& rhs);
is preferred to something like
ostream& operator<<(obj const& rhs);
But I can't quite see why should I use one or the other.
My personal case is:
friend ostream & operator<<(ostream &os, const Paragraph& p) {
return os << p.to_str();
}
But I could probably do:
ostream & operator<<(ostream &os) {
return os << paragraph;
}
What rationale should I base this decision on?
Note:
Paragraph::to_str = (return paragraph)
where paragraph's a string.
The problem here is in your interpretation of the article you link.
Equality
This article is about somebody that is having problems correctly defining the bool relationship operators.
The operator:
Equality == and !=
Relationship < > <= >=
These operators should return a bool as they are comparing two objects of the same type. It is usually easiest to define these operators as part of the class. This is because a class is automatically a friend of itself so objects of type Paragraph can examine each other (even each others private members).
There is an argument for making these free standing functions as this lets auto conversion convert both sides if they are not the same type, while member functions only allow the rhs to be auto converted. I find this a paper man argument as you don't really want auto conversion happening in the first place (usually). But if this is something you want (I don't recommend it) then making the comparators free standing can be advantageous.
Streaming
The stream operators:
operator << output
operator >> input
When you use these as stream operators (rather than binary shift) the first parameter is a stream. Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.
It is also traditional for these objects to return a reference to a stream object so you can chain stream operations together.
#include <iostream>
class Paragraph
{
public:
explicit Paragraph(std::string const& init)
:m_para(init)
{}
std::string const& to_str() const
{
return m_para;
}
bool operator==(Paragraph const& rhs) const
{
return m_para == rhs.m_para;
}
bool operator!=(Paragraph const& rhs) const
{
// Define != operator in terms of the == operator
return !(this->operator==(rhs));
}
bool operator<(Paragraph const& rhs) const
{
return m_para < rhs.m_para;
}
private:
friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);
std::string m_para;
};
std::ostream & operator<<(std::ostream &os, const Paragraph& p)
{
return os << p.to_str();
}
int main()
{
Paragraph p("Plop");
Paragraph q(p);
std::cout << p << std::endl << (p == q) << std::endl;
}
You can not do it as a member function, because the implicit this parameter is the left hand side of the <<-operator. (Hence, you would need to add it as a member function to the ostream-class. Not good :)
Could you do it as a free function without friending it? That's what I prefer, because it makes it clear that this is an integration with ostream, and not a core functionality of your class.
If possible, as non-member and non-friend functions.
As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.
In some cases, like C++ streams, you won't have the choice and must use non-member functions.
But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.
About operator << and >> prototypes
I believe the examples you gave in your question are wrong. For example;
ostream & operator<<(ostream &os) {
return os << paragraph;
}
I can't even start to think how this method could work in a stream.
Here are the two ways to implement the << and >> operators.
Let's say you want to use a stream-like object of type T.
And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.
Generic operator << and >> function prototypes
The first being as functions:
// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return p_oInputStream ;
}
Generic operator << and >> method prototypes
The second being as methods:
// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return *this ;
}
// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return *this ;
}
Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).
And what if T is a C++ stream?
Here are the prototypes of the same << and >> operators for C++ streams.
For generic basic_istream and basic_ostream
Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:
// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
For char istream and ostream
The following code will work only for char-based streams.
// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
Rhys Ulerich commented about the fact the char-based code is but a "specialization" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).
Hope this will help.
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
The signature:
bool operator<<(const obj&, const obj&);
Seems rather suspect, this does not fit the stream convention nor the bitwise convention so it looks like a case of operator overloading abuse, operator < should return bool but operator << should probably return something else.
If you meant so say:
ostream& operator<<(ostream&, const obj&);
Then since you can't add functions to ostream by necessity the function must be a free function, whether it a friend or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).
Just for completion sake, I would like to add that you indeed can create an operator ostream& operator << (ostream& os) inside a class and it can work. From what I know it's not a good idea to use it, because it's very convoluted and unintuitive.
Let's assume we have this code:
#include <iostream>
#include <string>
using namespace std;
struct Widget
{
string name;
Widget(string _name) : name(_name) {}
ostream& operator << (ostream& os)
{
return os << name;
}
};
int main()
{
Widget w1("w1");
Widget w2("w2");
// These two won't work
{
// Error: operand types are std::ostream << std::ostream
// cout << w1.operator<<(cout) << '\n';
// Error: operand types are std::ostream << Widget
// cout << w1 << '\n';
}
// However these two work
{
w1 << cout << '\n';
// Call to w1.operator<<(cout) returns a reference to ostream&
w2 << w1.operator<<(cout) << '\n';
}
return 0;
}
So to sum it up - you can do it, but you most probably shouldn't :)
friend operator = equal rights as class
friend std::ostream& operator<<(std::ostream& os, const Object& object) {
os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
return os;
}
operator<< implemented as a friend function:
#include <iostream>
#include <string>
using namespace std;
class Samp
{
public:
int ID;
string strName;
friend std::ostream& operator<<(std::ostream &os, const Samp& obj);
};
std::ostream& operator<<(std::ostream &os, const Samp& obj)
{
os << obj.ID<< “ ” << obj.strName;
return os;
}
int main()
{
Samp obj, obj1;
obj.ID = 100;
obj.strName = "Hello";
obj1=obj;
cout << obj <<endl<< obj1;
}
OUTPUT:
100 Hello
100 Hello
This can be a friend function only because the object is on the right hand side of operator<< and argument cout is on the left hand side. So this can't be a member function to the class, it can only be a friend function.

Can this be done without using friends?

Can the following code (I only kept the relevant part) be converted to use a static member function rather than a friend free function? If not, why not? I tried to convert it to use a static member function in multiple different ways and failed (kept getting different compiler errors for different variations), but I gathered from the answer to this question that you could use either one to do the same things. Is this not technically true due to some property of C++ syntax? Where am I going wrong here?
class Tape {
public:
friend std::ostream &operator<<(std::ostream &, Tape &);
private:
char blank;
size_t head;
std::string tape;
}
std::ostream &operator<<(std::ostream &out, Tape &tape) {
out << tape.tape << std::endl;
for (size_t i = 0; i < tape.head; i++)
out << ' ';
out << '^' << std::endl;
return out;
}
According to the C++ Standard
6 An operator function shall either be a non-static member function or
be a non-member function and have at least one parameter whose type is
a class, a reference to a class, an enumeration, or a reference to an
enumeration.
So you may not define operator << as a static mamber function of the class.
Nevertheless inside the definition of the operator you may use static member functions.
For example
#include <iostream>
class A
{
private:
int x = 10;
public:
static std::ostream & out( std::ostream &os, const A &a )
{
return ( os << a.x );
}
};
std::ostream & operator <<( std::ostream &os, const A &a )
{
return ( A::out( os, a ) );
}
int main()
{
A a;
std::cout << a << std::endl;
return 0;
}
Opposite to C++ in C# operator functions are defined as static.:)
Since the std::ostream argument is the left hand side of the operator, it can't be a member of your class (static or otherwise).
So it has to be a free function, because you can't add members to std::ostream.
It doesn't have to be a friend though, it could instead call a public member.
I personally prefer this method, as it doesn't expose anything to the outside.
class Tape {
public:
void print(std::ostream &out) const
{
out << tape << std::endl;
for (size_t i = 0; i < head; i++)
out << ' ';
out << '^' << std::endl;
}
};
std::ostream& operator<<(std::ostream &out, const Tape &tape)
{
tape.print(out);
return out;
}

Given a base class as a parameter, how do I use op<< overload to print the characteristics of a derived class if one is passed?

This is for a homework assignment.
I have a base class Item and a derived class Book.
I have op<< overloaded in Item class:
ostream& operator<<(ostream& out, const Item* const item)
{
out << item->getName() << endl;
return out;
}
As well as in Book class:
ostream& operator<<(ostream& out, const Book* const b)
{
out << b->getPages() << endl;
return out;
}
However only the Item operator is used when I run my code, and it does not print the pages for a book. I have made sure that a "book" gets printed, not just the base class. From the material I've read it seems that overloading the operators for both the base and derived classes is what you're supposed to do, so I'm not sure why my book info doesn't get printed.
You can use polymorphism instead of overloading: add a virtual print method to the classes:
class Item
{
public:
virtual void print(std::ostream& o) const
{
out << getName() << endl;
}
....
};
class Book : public Item
{
public:
virtual void print(std::ostream& o) const
{
out << getPages() << endl;
}
....
};
then use a single ostream& operator<<:
ostream& operator<<(ostream& out, const Item& item)
{
item.print(out);
return out;
}
then
Item* i1 = new Item(....);
Item* i2 = new Book(....);
std::cout << *i1 << " " << *i2 << std::endl;
delete i1;
delete i2;
If you change the derived class function's signature, it's no longer an override of the base class member function.
"However only the Item operator is used when I run my code" - this behaviour might be because you apply it to the pointer*/reference& on the base class;
If you have a container in which you want to store instances of different classes what are derived from the same base class and apply to all of them operator<<, which behaviour will depend on the class of instance for each it is invoked, you have to make sure that:
1.There is at least one virtual method in you base class (this will cause compiler to generate
virtual table for that class and later this table can be used by operator dynamic_cast)
2. Enable RTTI (run-time type identification) in your project : project/c++/language enable RTTI support
3. implement operator<< using the following idea:
ostream& operator<<(ostream& out, const Item& item)
{
if (Book* pBook = dynamic_cast<Book*>(&item)
{
out << pBook ->getName() << endl;
}
if (OtherDerivedClassName* pOtherDerivedClass = dynamic_cast<OtherDerivedClassName*>(&item)
{
// do other interesting things
}
return out;
}

'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?

In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is printed.
Here's what I tried to do:
ostream & Score::operator<< (ostream & os, Score right)
{
os << right.getPoints() << " " << right.scoreGetName();
return os;
}
Here are the errors returned:
score.h(30) : error C2804: binary 'operator <<' has too many parameters
(This error appears 4 times, actually)
I managed to get it working by declaring the overload as a friend function:
friend ostream & operator<< (ostream & os, Score right);
And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member).
Why does this work, yet the former piece of code doesn't?
Thanks for your time!
EDIT
I deleted all mentions to the overload on the header file... yet I get the following (and only) error. binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)
How come my test, in main(), can't find the appropriate overload? (it's not the includes, I checked)
Below is the full score.h
#ifndef SCORE_H_
#define SCORE_H_
#include <string>
#include <iostream>
#include <iostream>
using std::string;
using std::ostream;
class Score
{
public:
Score(string name);
Score();
virtual ~Score();
void addPoints(int n);
string scoreGetName() const;
int getPoints() const;
void scoreSetName(string name);
bool operator>(const Score right) const;
private:
string _name;
int _points;
};
#endif
Note: You might want to look at the operator overloading FAQ.
Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// stream obj's data into os
return os;
}
Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either.
Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming
class T {
public:
void stream_to(std::ostream&) const {os << obj.data_;}
private:
int data_;
};
and call that from the operator:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
obj.stream_to(os);
return os;
}
or make the operator a friend
class T {
public:
friend std::ostream& operator<<(std::ostream&, const T&);
private:
int data_;
};
so that it can access the class' private parts:
inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
os << obj.data_;
return os;
}
Let's say you wanted to write an operator overload for + so you could add two Score objects to each other, and another so you could add an int to a Score, and a third so you could add a Score to an int. The ones where a Score is the first parameter can be member functions of Score. But the one where an int is the first parameter can't become member functions of int, right? To help you with that, you're allowed to write them as free functions. That is what is happening with this << operator, you can't add a member function to ostream so you write a free function. That's what it means when you take away the Score:: part.
Now why does it have to be a friend? It doesn't. You're only calling public methods (getPoints and scoreGetName). You see lots of friend operators because they like to talk directly to the private variables. It's ok by me to do that, because they are written and maintained by the person maintaing the class. Just don't get the friend part muddled up with the member-function-vs-free-function part.
You're getting compilation errors when operator<< is a member function in the example because you're creating an operator<< that takes a Score as the first parameter (the object the method's being called on), and then giving it an extra parameter at the end.
When you're calling a binary operator that's declared as a member function, the left side of the expression is the object the method's being called on. e.g. a + b might works like this:
A a;
B b
a.operator+(b)
It's typically preferable to use non-member binary operators (and in some cases -- e.g. operator<<for ostream is the only way to do it. In that case, a + b might work like this:
A a;
B b
operator+(a, b);
Here's a full example showing both ways of doing it; main() will output '55' three times:
#include <iostream>
struct B
{
B(int b) : value(b) {}
int value;
};
struct A
{
A(int a) : value(a) {}
int value;
int operator+(const B& b)
{
return this->value + b.value;
}
};
int operator+(const A& a, const B& b)
{
return a.value + b.value;
}
int main(int argc, char** argv)
{
A a(22);
B b(33);
std::cout << a + b << std::endl;
std::cout << operator+(a, b) << std::endl;
std::cout << a.operator+(b) << std::endl;
return 0;
}