Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I print an object of the class using printf()?

Tags:

c++

printf

cout

I have some code like this:

class Point {
public:
    int x,y;
    Point() : x(1), y(1) {}
}

Can I print object of that class using printf():

int main()
{
    Point point;
    printf("%o",point);
    return 0;
}

or I have to overload operator<< and use std::cout:

std::ostream& operator<<(std::ostream& os, Point const& p)
{
    os << p.x << "," << p.y;
    return os;
}
int main()
{
    Point point;
    std::cout << point;
    return 0;
}
like image 625
nathiss Avatar asked Feb 15 '16 16:02

nathiss


1 Answers

Can I print object of that class using printf()?

No. printf is not extensible in that sense.

Your best option is to overload operator<< between std::ostream and Point.

PS I suggest changing the argument type to Point const&.

like image 84
R Sahu Avatar answered Oct 23 '22 20:10

R Sahu