Passing pointer to function that accepts reference in c++ - c++

I guess this is a n00b question because I couldn't find anything about it on web...
Here is Point class:
class Point {
public:
Point();
Point(double x, double y);
double getX() const;
double getY() const;
void setX(double);
void setY(double);
friend std::ostream& operator<<(std::ostream& os, const Point& obj);
private:
double x;
double y;
};
And here is an implementation of operator<< function:
inline std::ostream& operator<<(std::ostream& os, const Point& obj) {
os << "(" << obj.getX() << "," << obj.getY() << ")";
return os;
}
Now, in main function I have Point *p;... How can I print it using std::cout?

You need to dereference your pointer but as pointers can be null, you should check first.
if( p != nullptr )
std::cout << *p << std::endl;
or even just
if( p )
std::cout << *p << std::endl;
And now, go and read this in our community wiki, hopefully it will provide you the answers.
What are the differences between a pointer variable and a reference variable in C++?

So, I finally found out where was the problem.
Although all tutorials, books and even c++ reference agree that inline directive can be ignored by the compiler, it turns out that when I remove inline keyword from implementation of an overloaded function everything works.

Related

printing an unordered map made by structs c++ [duplicate]

myclass is a C++ class written by me and when I write:
myclass x;
cout << x;
How do I output 10 or 20.2, like an integer or a float value?
Typically by overloading operator<< for your class:
struct myclass {
int i;
};
std::ostream &operator<<(std::ostream &os, myclass const &m) {
return os << m.i;
}
int main() {
myclass x(10);
std::cout << x;
return 0;
}
You need to overload the << operator,
std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
os << obj.somevalue;
return os;
}
Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.
If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.
it's very easy, just implement :
std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
os << foo.var;
return os;
}
You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)
Even though other answer provide correct code, it is also recommended to use a hidden friend function to implement the operator<<. Hidden friend functions has a more limited scope, therefore results in a faster compilation. Since there is less overloads cluttering the namespace scope, the compiler has less lookup to do.
struct myclass {
int i;
friend auto operator<<(std::ostream& os, myclass const& m) -> std::ostream& {
return os << m.i;
}
};
int main() {
auto const x = myclass{10};
std::cout << x;
return 0;
}
Alternative:
struct myclass {
int i;
inline operator int() const
{
return i;
}
};

operator << overloading often fails if operator is const?

If I want to overload the << operator to use cout on a class, it should look like this:
template <typename coutT>
friend ostream& operator << (ostream &, const vector3D<coutT>&);
inside the class, and
template <typename coutT>
ostream& operator << (ostream & os,const vector3D<coutT>& v)
{
os << "x: " << v.x<< " y: " << v.y << " z: " << v.z;
return os;
}
on the outside. Please take note of the const at the second operand.
This sample of code works just fine. Now to the problem.
If I were to write the overload function using the getters for the fields, instead of addressing them directly (since operator<< is a friend), my compiler would throw an error:
template <typename coutT>
ostream& operator << (ostream & os,const vector3D<coutT>& v)
{
os << "x: " << v.getX() << " y: " << v.getY() << " z: " << v.getZ();
return os;
}
The error:
(VisualStudio2012) errorC2662: "this-pointer cannot be converted from "const vector3D" in "vector3D&""
An important note is that deleting the "const" at the second operand so that it's like
ostream& operator << (ostream & os,vector3D<coutT>& v){...}
ended compiler errors, but since I don't want to change v, it should really be a const.
I should also mention that I think it may have to do with method calls in general, but I'm not sure.
edit:
So it is solved, declaring functions as const sticks to const-correctness.
The error message explains it in the way that it cannot cast the const type to a non-const one.
btw.: I'm actually impressed about the quick responses.
The getter function should be declared const if you want to use it that way.
For example
int getValue() const {
return x;
}
Complete example:
#include <iostream>
#include <vector>
using namespace std;
class Foo {
int x;
public:
Foo(int a) : x(a) {
}
int getValue() const {
return x;
}
friend ostream & operator<<(ostream & out, const Foo & foo) {
return out << foo.getValue();
}
};
int main() {
vector<Foo> foo_vec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (vector<Foo>::iterator it = foo_vec.begin(); it != foo_vec.end(); it++) {
cout << *it << ", ";
}
return 0;
}
Your problem is that you didn't mark the get functions const:
They need to look like this:
double getX() const;
You need to make the accessor functions const:
struct V
{
int getX() const { /* ... */ }
^^^^^
};
Only const member functions can be invoked on constant object values. In turn, const member functions cannot mutate the object. Thus const-correctness guarantees that a constant value cannot be mutated by invoking any of its member functions.

How to get THIS when overloading operator in C++

I'm a student learning c++. today, I was making a operator overload function to use it in 'cout'. following is a class that contains name, coordinates, etc.
class Custom {
public:
string name;
int x;
int y;
Custom(string _name, int x, int y):name(_name){
this->x = x;
this->y = y;
}
int getDis() const {
return static_cast<int>(sqrt(x*x+y*y));
}
friend ostream& operator << (ostream& os, const Custom& other);
};
ostream& operator << (ostream& os, const Custom& other){
cout << this->name << " : " << getDis() << endl;; // error
return os;
}
However, this code isn't working because of 'THIS' keyword that I was expecting it points to the object. I want to show the object's name and distance value. How can I solve it? I think it is similar with Java's toString method so that it will be able to get THIS.
Thanks in advance for your answer and sorry for poor english. If you don't understand my question don't hesitate to make a comment.
this is available only in member functions, but your operator<< is not a class member (declaring it as friend does not make it a member). It is a global function, as it should be. In a global function, just use the arguments you are passing in:
ostream& operator << (ostream& os, const Custom& other)
{
os << other.name << " : " << other.getDis() << endl;
return os;
}
Also note os replaced cout in the code above. Using cout was an error - the output operator should output to the provided stream, not to cout always.

<< Operator overloading error in C++

I'm a C++ beginner, trying to learn from online videos. In of the operator overloading examples in the lectures the following code is there and gives the error
error: no match for 'operator<<' in 'std::cout << operator+(((point&)(& p1)), ((point&)(& p2)))'compilation terminated due to -Wfatal-errors.
on the line marked with comment. Can someone please tell what's wrong in the code? I am just trying what the professor explained in the lecture but can't compile.
===============
#include <iostream>
using namespace std;
class point{
public:
double x,y;
};
point operator+ (point& p1, point& p2)
{
point sum = {p1.x + p2.x, p1.y + p2.y};
return sum;
}
ostream& operator<< (ostream& out, point& p)
{
out << "("<<p.x<<","<<p.y<<")";
return out;
}
int main(int argc, const char * argv[])
{
point p1 = {2,3};
point p2 = {2,3};
point p3;
cout << p1 << p2;
cout << p1+p2; // gives a compliation error
return 0;
}
It's just a problem with const correctness. Your operator+ returns a temporary, so you can't bind a non-const reference to it when calling operator<<. Make the signature:
ostream& operator<< (ostream& out, const point& p)
While you don't need to do it to fix this compilation error, you won't be able to add const points unless you fix the operator+ similarly:
point operator+(const point& p1, const point& p2)
Change the parameter type from point& to const point& for operator+ and operator<<. Non-const reference cannot bind to a temporary (which is returned by operator+) and that is causing the compile error.
The reason is the second parameter should be a const reference. (you don't want it gets modified, right?) So, it is like,
std::ostream& operator<< (std::ostream &out, const Point &p)
{
out << "(" << p.x << ", " << p.y << ")";
return out;
}

Function returning to ostream

I wonder if there is any possibility to create function returning some part of ostream, like in example:
#include <iostream>
class Point {
public:
Point(int x, int y){
this->x = x;
this->y = y;
}
?? getXY(){ // I wish this function returned ostream
return ??;
}
private:
int x,y;
};
int main() {
Point P(12,7);
std::cout << "(x,y) = " << P.getXY(); // (12, 7);
}
I wish the output was:
(x,y) = (12,7)
I don't want getXY() to return any string or char array. May I somehow return part of stream?
Generally this is done by overloading the stream insertion operator for your class, like this:
class Point {
public:
Point(int x, int y){
this->x = x;
this->y = y;
}
int getX() const {return x;}
int getY() const {return y;}
private:
int x,y;
};
std::ostream& operator<<(std::ostream& out, const Point& p)
{
out << "(x,y) =" << p.getX() << "," << p.getY();
return out;
}
Used as:
Point p;
cout << p;
Why not just implement operator << for your class? It would do exactly what you want.
If you only need to print one sort of output, just override operator<< in your containing class. But, if you need to print different sorts of output according in different contexts, you might try creating objects of different proxy classes.
The proxy object could hold a reference to Point, and print it (or portions of it) according to your needs.
I would make the proxy objects private member classes of Point to restrict their visibility.
EDIT Removed sample -- I didn't notice this was homework.
In addition to your Point code, you can use a helper function (below, display()) as an alternative to overloading:
std::ostream& display(std::ostream &os,Point &p) const {
os<< p.x << p.y ;
return os;
}
int main() {
Point p;
display(std::cout,p);
// This will call the display function and
// display the values of x and y on screen.
} //main
The display function can be made a friend of class Point if it needs to access private members.