I'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could override the toString() method for similar purpose.
In C++ you can overload operator<< for ostream and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
You can also do it this way, allowing polymorphism:
class Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Base: " << b << "; ";
}
private:
int b;
};
class Derived : public Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Derived: " << d << "; ";
}
private:
int d;
}
std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }
In C++11, to_string is finally added to the standard.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:
#include <sstream>
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace
std::stringstream is located in the <sstream> header.
The question has been answered. But I wanted to add a concrete example.
class Point{
public:
Point(int theX, int theY) :x(theX), y(theY)
{}
// Print the object
friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
int x;
int y;
};
ostream& operator <<(ostream& outputStream, const Point& p){
int posX = p.x;
int posY = p.y;
outputStream << "x="<<posX<<","<<"y="<<posY;
return outputStream;
}
This example requires understanding operator overload.
Related
Imagine a setup as follows. How do I invoke the base class cout from within the derived class cout? I could use the getBrand() method, but I feel like I should be able to directly access the base class' cout friend function.
I hacked a bit, and tried this.Brand and also just Brand. No luck.
class Brand {
public:
Brand(std::string brand):brand_(brand) {};
friend std::ostream & operator << (std::ostream & out, const Brand & b) {
out << b.brand_ << ' ';
return out;
}
std::string getBrand()const { return brand_; }
private:
std::string brand_;
}
class Cheese : public Brand {
public:
Cheese(std::string brand, std::string type):Brand(brand), type_(type) {};
friend std::ostream & operator << (std::ostream & out, const Cheese & c) {
out << /* THIS.BRAND?! BRAND?! getBrand() meh.. */ << ' ' << c.type_ << std::endl; // <-- HERE
return out;
}
private:
std::string type_;
}
int main() {
Cheese c("Cabot Clothbound", "Cheddar");
std::cout << c << std::endl;
}
DESIRED OUTPUT
Cabot Clothbound Cheddar
You could invoke the overloaded operator << of the Base class from the derived class. Since, you declared the operator as a friend, you could simply cast the the derived class to a base class:
class Cheese : public Brand {
public:
Cheese(std::string brand, std::string type):Brand(brand), type_(type) {};
friend std::ostream & operator << (std::ostream & out, const Cheese & c) {
//ADDED
out << static_cast<const Brand&>(c) << c.type_ << std::endl;
return out;
}
private:
std::string type_;
};
Output:
Cabot Clothbound Cheddar
See it Live
Cast it, like this:
friend std::ostream& operator<<(std::ostream& out, const Cheese& c)
{
out << static_cast<const Brand &>(c);
out << c.type_ << std::endl;
return out;
}
All other answers are responding correctly to your specific question, but whenever you'll try to use polymorphism like this:
Brand const &c = Cheese("Cabot Clothbound", "Cheddar");
std::cout << c << std::endl;
operator << corresponding to Brand will be called instead of Cheese's.
The good way to do it is to use a virtual print member function:
class Brand {
public:
Brand(std::string const & brand):brand_(brand) {}
virtual ~Brand() {}
virtual void print(std::ostream & out) const {
out << brand_;
}
std::string const & getBrand()const { return brand_; }
private:
std::string brand_;
};
class Cheese : public Brand {
public:
Cheese(std::string const & brand, std::string const & type):Brand(brand), type_(type) {}
void print(std::ostream & out) const override {
Brand::print(out); // calling base print()
out << ' ' << type_ << std::endl;
}
private:
std::string type_;
};
Then, you only need a single operator << for the base class which will call your print virtual member function:
std::ostream & operator << (std::ostream & out, const Brand & b) {
b.print(out);
return out;
}
DEMO
You obviously can't do anything like Brand::operator<<, because both operator<< are defined as friend and thus they are not member functions.
If you want to invoke operator<<(std::ostream&, const Brand&), you just have to pass correct types to that, and since Derived classes can be easily casted to Base classes, you can just do
friend std::ostream & operator << (std::ostream & out, const Cheese & c) {
out << static_cast<const Brand&>(c) << ' ' << c.type_ << std::endl;
return out;
}
For example, I've written a class called Length:
class Length {
public:
void setValue(float);
private:
float value_;
};
void
Length::setValue(float newValue) {
value_ = newValue;
}
void print(float value) {
std::cout << value;
}
void computeStuff(float value) {
//do the computing
}
int main() {
Length width;
width.setValue(5);
std::cout << width; // <-- this is actually just an example
//what I actually want is:
print(width); // print 5
//or perhaps even
computeStuff(width);
return 0;
}
Now how to make width return value_ or 5?
Technically, width is not an instance name, it's a name of a variable of type Length. You can change your code to retrieve a variable in two ways:
Add a friend operator << for Length that does the printing, or
Add an implicit conversion operator from Length to float.
The first approach works only for output. You cannot pull the value directly:
friend ostream& operator <<(ostream& out, const Length& len) {
out << len.value_;
return out;
}
The second approach looks like this:
class Length {
...
public:
operator float() const { return value_; }
};
You must overload operator<< for your custom type, something like:
class Length
{
..
friend std::ostream& operator<<(std::ostream& os, const Length& o);
..
}
std::ostream& operator<<(std::ostream& os, const Length& o)
{
os << o.value_;
return os;
}
Mind that this
must be non member
is nothing special , just an operator overload applied to a standard way of inserting things into stream of <iostream>
You need to define an operator() method to print the value 5.
You need to overload the << operator for your class. You could also use a function to do the operator's work.
Operator <<
#include <iostream>
class Length {
friend std::ostream& operator<<(std::ostream& os, const Length& l);
public:
void setValue(float);
private:
float value_;
};
void
Length::setValue(float newValue) {
value_ = newValue;
}
std::ostream& operator<<(std::ostream& os, const Length& l)
{
os << l.value_;
return os;
}
int main() {
Length width;
width.setValue(5);
std::cout << width << std::endl; // print 5
return 0;
}
function:
#include <iostream>
class Length {
friend std::ostream& print(std::ostream &,const Length &l);
public:
void setValue(float);
private:
float value_;
};
void
Length::setValue(float newValue) {
value_ = newValue;
}
std::ostream& print(std::ostream &os, const Length &l)
{
os << l.value_;
return os;
}
int main() {
Length width;
width.setValue(5);
print(std::cout, width) << std::endl;
return 0;
}
I have a class A, for which I have defined an (overloaded) stream insertion operator. I publicly derive a class B from this class A, which has an additional data member. Therefore I'll need to redefine the overloaded stream insertion operator for the derived class and I've do it this way:
#include <iostream>
using namespace std;
class A {
int i;
char c;
public:
A(int i = 0, char c = ' ') {
this->i = i;
this->c = c;
}
friend ostream& operator << (ostream&, const A&);
};
class B : public A {
double d;
public:
B(int i = 0, char c = ' ', double d = 0.0) : A(i, c), d(d) {}
friend ostream& operator << (ostream&, const B&);
};
ostream& operator << (ostream& out, const A& a) {
out << "\nInteger: " << a.i << "\nCharacter: " << a.c << endl;
return out;
}
ostream& operator << (ostream& out, const B& b) {
out << b;
out << "\nDouble: " << b.d << endl;
return out;
}
int main() {
A a(10, 'x');
B b(20, 'y', 5.23);
cout << b;
return 0;
}
Question-1: Is this an appropriate technique of doing so? If not, kindly let me know where I'm going wrong.
Question-2: On running, this program crashes. Why so?
One common way to support this is to have the overloaded operator invoke a virtual member function:
class A {
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
os << "A\n";
return os;
}
};
class B : public A {
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
// This can use the base class writer like:
A::write(os);
os << "B\n";
return os;
}
};
Then the operator overload just invokes that member function:
std::ostream &operator<<(std::ostream &os, A const &a) {
return a.write(os);
}
Since write is virtual and you're passing the A by (const) reference, this invokes the correct member function based on the actual type (i.e., A::write if the object is really an instance of A, and B::write if it's an instance of B).
For example, we could exercise these something like this:
int main() {
A a;
B b;
std::cout << a << "\n";
std::cout << b << "\n";
}
...which produces output like this:
A
A
B
In real use, you probably want to make the write functions protected, and make the operator<< a friend of A.
The program crashes because your second insertion operator calls itself:
ostream& operator << (ostream& out, const B& b) {
out << b; // <--YIKES!
out << "\nDouble: " << b.d << endl;
return out;
}
Generally this is a good approach, although I prefer to give the classes a public virtual print(ostream&) const function, and have the insertion operator call that.
I am learning C++, and learned that int-types are just premade classes. So I thought maybe i should try to create one.
What I want to do basically is a
normal class of int
int x;
x=7;
cout << x;
// Output is 7 on screen.
so similarly...
abc x;
x=7;
cout << x;
What would I put in
class abc{
\\ HERE!!!!!!
};
so I could do this
class SomeClass {
public:
int x;
SomeClass(int x) {
this->x = x;
}
};
int main(int argc, char *argv[]) {
SomeClass s = 5;
cout << s.x << "\n"; // 5
s = 17;
cout << s.x << "\n"; // 17
return 0;
}
But as you can see I have to use s.x to print the value - I just want to use 's'.
I am doing it as an experiment, I don't want to hear about how this method is good or bad, pointless or revolutionary, or can 't be done. I remember once I did it. But only by copying and pasting code that I didn't fully understand, and have even forgotten about.
and learned that int, types, are just premade classes
This is completely false. Still, you have complete control on how your class will behave in expressions, since you can overload (almost) any operator. What you are missing here is the usual operator<< overload that is invoked when you do:
cout<<s;
You can create it like this:
std::ostream & operator<<(std::ostream & os, const SomeClass & Right)
{
Os<<Right.x;
return Os;
}
For more information, see the FAQ about operator overloading.
the << and >> are basically function names. you need to define them for your class. same with the +, -, * and all the other operators. here is how:
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
You need to overload operator<< for your class, like so:
class abc
{
public:
abc(int x) : m_X(x) {}
private:
int m_X;
friend std::ostream& operator<<(std::ostream& stream, const abc& obj);
};
std::ostream& operator<<(std::ostream& os, const abc& obj)
{
return os << obj.m_X;
}
You don't have to friend your operator<< overload unless you want to access protected/private members.
You must define in your class abc cast operator to int and assignment operator from int, like in this template class:
template <class T>
class TypeWrapper {
public:
TypeWrapper(const T& value) : value(value) {}
TypeWrapper() {}
operator T() const { return value; }
TypeWrapper& operator (const T& value) { this->value = value; return *this; }
private:
T value;
};
int main() {
TypeWrapper<int> x;
x = 7;
cout << x << endl;
}
You want to overload the output operator:
std::ostream& operator<< (std::ostream& out, SomeClass const& value) {
// format value appropriately
return out;
}
Which operator do I have to overload if I want to use sth like this?
MyClass C;
cout<< C;
The output of my class would be string.
if you've to overload operator<< as:
std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
//use out to print members of obj, or whatever you want to print
return out;
}
If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can delegate the work to some public function of the class.
For example, suppose you've a point class defined as:
struct point
{
double x;
double y;
double z;
};
Then you can overload operator<< as:
std::ostream& operator<<(std::ostream& out, const point & pt)
{
out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
return out;
}
And you can use it as:
point p1 = {10,20,30};
std::cout << p1 << std::endl;
Output:
{10,20,30}
Online demo : http://ideone.com/zjcYd
Hope that helps.
The stream operator: <<
You should declare it as a friend of your class:
class MyClass
{
//class declaration
//....
friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}
std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
//logic here
}
You should implement operator<< as a free function.