Thread: Overloading << Issue

  1. #1
    Registered User
    Join Date
    Sep 2005

    Overloading << Issue

    It is to my understanding to overload the output operator (<<) you must declare the function as standalone - OK.

    And also if you want to access the private data you need to make it a "friend" of the class - OK.

    But when I compile, I get a undeclared identifier error.. Any help would be appreciated.

    Friend declaration in my .h file under public:
    friend	ostream& operator<<(ostream&, GList);
    Stand-alone function (end and list are private data members):
    ostream& operator<<(ostream& out, GList list)
    	for(int i = 0; i < end; i++)
    		out << list[i];
    	return out;
    Output errors:
    error C2065: 'end' : undeclared identifier
    error C2676: binary '[' : 'GList' does not define this operator or a conversion to a type acceptable to the predefined operator

    Thanks in advance..

  2. #2
    Registered User
    Join Date
    Apr 2003
    See if this helps:
    #include <iostream>
    using namespace std;
    class GList
    	int end;
    	int* pArray;
    	GList(int size, int* anArray) 
    		end = size;
    		pArray = anArray;
    	friend ostream& operator<<(ostream&, const GList&);
    ostream& operator<<(ostream& out, const GList& list)
    	for(int i=0; i<list.end; i++)
    	return out;
    int main()
    	int size = 3;
    	int arr[] = {10, 20, 30};
    	GList myList(size, arr);
    	return 0;
    Note: you should make the GList parameter a reference to avoid having to copy the object for the function, and you should make it a const since the function doesn't need to change the GList object.
    Last edited by 7stud; 10-27-2005 at 02:24 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overloading <<
    By msshapira in forum C++ Programming
    Replies: 2
    Last Post: 05-06-2009, 02:11 PM
  2. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  3. Overloading the << operator.
    By antex in forum C++ Programming
    Replies: 5
    Last Post: 05-31-2005, 01:37 AM
  4. << and >> overloading
    By Armatura in forum C++ Programming
    Replies: 2
    Last Post: 12-07-2003, 06:19 PM
  5. Overloading << for my class
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-30-2003, 02:45 AM