Calling struct = returning value?

Aug 24, 2016 at 3:25pm
is there a way to make the code below print 3?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

struct pint
{
	int value;
	void operator=(int newValue)
	{
		value = newValue;
	}
};

int main() {
	pint a;
	a = 3;
	cout << a;
	return 0;
}
Aug 24, 2016 at 3:48pm
If you are going to be declaring methods, you should just declare a class.

In C++, the only difference between struct and class is the default visibility of members (class is private, struct is public).

But for people familiar with C, structs are used there to hold data only, and it's generally advised to follow that pattern and only use structs when it'll only hold data.

As for how to make it print out, you could make a method that returns the integer
1
2
3
4
5
6
7
8
9
10
11
12
struct pint //Recommend 'class pint' instead
{
  ...
  int get_value()
  {
    return value;
  }
...
};
...
//Somewhere else
cout << a.get_value();
or you could overload the << operator for pint.

A more technical reference for operator overloading: http://en.cppreference.com/w/cpp/language/operators
An example article: https://isocpp.org/wiki/faq/operator-overloading (what better place than isocpp?)
Aug 24, 2016 at 3:53pm
yeah, I could just do cout << a.value but as mentioned above, I asked about a specific code, overloading << is not an option, as I want to return "value" whenever calling struct at all times, not only when accessing it with << operator
Last edited on Aug 24, 2016 at 3:57pm
Aug 24, 2016 at 3:58pm
You want a type conversion operator:

http://en.cppreference.com/w/cpp/language/cast_operator

(or else overload the arithmetic operators)
Last edited on Aug 24, 2016 at 3:58pm
Aug 24, 2016 at 3:58pm
I don't think this 3 + a expression can be made valid without overloading operator+(int, const pint &).
Aug 24, 2016 at 4:08pm
As you code stands now, you cannot make it print '3' without adding to it.

To have cout << a print, you would need to overload the << operator and define how to print that.
1
2
3
4
5
std::ofstream& operator << (std::ofstream &out)
{
  out << "Value: " << value;
  return out;
}

To have int b = 3 + a; work, you would need to declare and define a conversion to type int
1
2
3
4
operator int() const
{
  return value; 
}

(or overload the + operator)
Last edited on Aug 24, 2016 at 4:10pm
Topic archived. No new replies allowed.