Compiling the following the class in the main program returns error C2784.

What could be causing the problem?

#include <iostream> // Include input/output stream
#include <cmath>

class threevector
{

public:
	double xcoord, ycoord, zcoord;
	
	// Default constructor
	threevector()
	{
		xcoord = 0.0;
		ycoord = 0.0;
		zcoord = 0.0;
	}
    
	// Cartesian constructor
	threevector(double x, double y, double z)
	{
		xcoord = x;
		ycoord = y;
		zcoord = z;
	}

	// Method to print out contents to screen
	void print()
	{
		std::cout << xcoord << '\t'
           		      << ycoord << '\t'
				  << zcoord << std::endl;
	}

	//Method to print out contents to file
	void print(std::ofstream fout)
	{
		fout << xcoord << '\t'
			 << ycoord << '\t'
			 << zcoord << std::endl;
	}
	
};

Unfortunately, most of us don't know what an error is just by the number. Since it starts with a 'C' we know it's a compiler error, not a linker error, but that's really it. What specifically is the error reported (not just the number, the text description)?

I suspect the problem is with your threevector::print() function. Your argument really should be a reference to an existing file stream, not a copy of one.

Edited 5 Years Ago by Fbody: n/a

Thanks for the point!

I have modified the type of the argument in the print function to ofstream&.
Even then, the code does not compile. (I guess that's because the the argument does not refer to any ofstream object in the main program. Am I right?)

Next, I defined an ofstream object in the main program and then the code compiles.

My question is:
why should my argument be a reference to an existing file stream, not a copy of one? Please reply.

A reference allows you to make modifications to the argument/parameter and have those modifications be reflected in the original scope of the variable, which is necessary for the data stream to work properly.

"A reference allows you to make modifications to the argument/parameter and have those modifications be reflected in the original scope of the variable":

Ok! This I understand.

"which is necessary for the data stream to work properly.":

Why is it necessary for the data stream to work properly?

Inside a data stream, especially a file stream, there are pointers that keep track of your current read and write locations. If you can't modify the stream, the pointers will get messed up and break your stream.

This article has been dead for over six months. Start a new discussion instead.