C++ overloading question

Hi,

I just wanna ask about this particular part of a code inside an overloading operator function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
template<typename TYPE>
BOOL bFile::operator >> ( std::vector<TYPE> &VALUE )
{
	BOOL bOK(FALSE);
	DWORD dwSize(0);

	VALUE.clear();

	bOK = operator >> ( dwSize );
	if ( !bOK )					
           return FALSE;
	
	if ( dwSize==0 )
           return TRUE;

	VALUE.reserve(dwSize);
	for ( DWORD i=0; i<dwSize; ++i )
	{
		TYPE tVALUE;
		bOK = ReadBuffer ( &tVALUE, DWORD(sizeof(TYPE)) );
		if ( !bOK )
                   return FALSE;

		VALUE.push_back ( tVALUE );
	}

	return TRUE;
}

bOK = operator >> ( dwSize );
My question is how does this work? I'm not sure if it works like a variable when it's assigning a value using parenthesis. Maybe there was somebody that have posted like this before but I just don't know what it's called if it was some kind of a function.
Last edited on
To call this function, you do not use:
bOK = operator >> ( dwSize );
Assuming that bOK is a bFile and dwSize is a std::vector, you just need to use:
bOK >> dwSize;

The operator functions are meant to make our lives easier. The class that holds the operator is always the left-hand side of the operator and whatever type is used as the argument is the right hand side.

That lets us do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Complex
{
public:
    double real;
    double imag;
    Complex operator+ (Complex& rhs)
    {
        Complex output;
        output.real = real + rhs.real;
        output.imag = imag + rhs.imag;
        return output;
    }
}

Now we can call this function with the + operator which will let us add two complex numbers:
1
2
Complex A, B;
Complex C = A + B;
Last edited on
Stewbond wrote:
To call this function, you do not use:
bOK is a boolean variable. so you need to call it like jhomers showed above. Since operator >> probably returns a stream (or something else that itself has an operator for boolean) and you want the result of that (if it's ok)

This bOK >> dwSize; will lead to compiler error

jhomers wrote:
My question is how does this work?
It's a function call
It is obvious that class bFile contains at least two overload operators:

BOOL bFile::operator >> ( std::vector<TYPE> & );
BOOL bFile::operator >> ( DWORD );

Inside the first operator definition there is a call to the second overload operator

bOK = operator >> ( dwSize );

that reads an object of type DWORD.



Here's a example:
1
2
3
4
5
6
bFile file;
std::vector<int> value;

BOOL Result = file >> value;
// bFile::operator>> is called, with a std::vector<int> parameter


EDIT: I quote the next Stewbond's comment:

Stewbond wrote:
Ah, I see! I didn't actually read the function contents.
Last edited on
bOK = operator >> ( dwSize ); is equivalent to
bOK = (*this) >> dwSize;
Ah, I see! I didn't actually read the function contents.
Topic archived. No new replies allowed.