Home # 4 comments

In our homework #4 assignment, some students may encounter a bug in the Visual C++ compiler. If you have applied Service Pack 3 for Visual Studio, you should not get this error, but we will discuss it here, and examine a work around that will allow you to complete your homework.

The Problem

The problem occurs with the use of the operator<< as a friend function of a class, which will access private data members of that class. Please note: The use of the friend keyword was not part of our homework assignment, and most students will not encounter any problems in doing the work as described.

Microsoft has acknowledged this to be a bug, and the following code will not compile without Service Pack 3, though it is perfectly valid C++ code:

#include <iostream>
using namespace std;

class MGString
{
public:
   friend ostream& operator<<( ostream& Dest, const MGString& Src );
   // portions removed for readability
protected:
   char* m_Str;
};

ostream& operator<<( ostream& Dest, const MGString& Src )
{
   Dest << Src.m_Str; // Access protected member in a friend function
   return( Dest );
}

Work Around

If you can not download or did not recieve Service Pack 3, then there is still another alternative to assist in getting your programs to work. You must create a foreward-reference for your class, and then prototype the functions that will be declared as friend functions. The following is a fixed version of the above demonstration:

#include <iostream>
using namespace std;

// Foreward reference:
class MGString;
// Prototype of friend function:
ostream& operator<<( ostream& Dest, const MGString& Src ); 

class MGString
{
public:
   friend ostream& operator<<( ostream& Dest, const MGString& Src );
   // portions removed for readability
protected:
   char* m_Str;
};

ostream& operator<<( ostream& Dest, const MGString& Src )
{
   Dest << Src.m_Str; // Access protected member in a friend function
   return( Dest );
}

The program should now compile cleanly.