New C++ coder w/difficulty on scope/visibility in queue example - c++

All,
I asked a question last week and I thank you for your tolerance in answering. I'm overall an inexperienced coder but have dabbled most of my life. This is the hardest language/class I've ever taken and it's driving me nuts that I can't get some of these concepts. I've done quite a bit of googling and found some helpful things but never something quite similar enough to fix what I've run into.
ALSO: I am not that familiar with the SO interface, so wasn't sure last time how to 'mark' an answer as the best to give credit to those who helped. I didn't see a way to respond to other smaller comments. A lot in here, but I want to do the right thing for you folks taking the time to help others.
The assignment is to create a queue class with five files described as follows:
QueueItem.h contains the class definition for QueueItem
QueueItem.cpp contains the member function implementations for QueueItem.
Queue.h contains the class definition for Queue.
Queue.cpp contains the member function implementations for Queue.
main.cpp contains the main() test function.
Queue.h
#pragma once
#include "QueueItem.h"
class Queue {
public:
Queue(); // ctor inits a new empty Queue
~Queue(); // dtor erases any remaining QueueItems
void addItem(const char* pData);
void removeItem();
void print();
void erase();
private:
QueueItem* _pHead; // always points to first QueueItem in the list
QueueItem* _pTail; // always points to the last QueueItem in the list
int _itemCounter; // always increasing for a unique id to assign to each new QueueItem
};
In Queue.cpp below, there are two places where I think the code should either be _pTail->_pNext or _pTail._pNext. If it's the ->, then I get C++ member (declared at line 21 of) is inaccessible but using the . gives C++ expression must have class type. This is definitely one of the places where I think it's a conceptual thing I'm not understanding because I think it should be the -> but have no idea how to make that accessible.
Queue.cpp
#include "Queue.h"
#include "QueueItem.h"
#include <iostream>
using namespace std;
void Queue::addItem(const char* pData) {
// dynamically create and init a new QueueItem object
QueueItem* pItem = new QueueItem(pData, ++_itemCounter);
if (0 == _pHead) // check for empty queue
_pHead = _pTail = pItem;
else {
// link new item onto tail of list using _pTail pointer
_pTail->_pNext = pItem; // links the current pTail to the new pItem
_pTail = pItem; // move the pTail to the new item
}
}
void Queue::removeItem() {
// check for empty queue
if (0 == _pHead)
{ // if empty, nothing to do
}
else
{
// pop top item off
QueueItem* popped = _pHead; // create popped to hold value of _pHead
_pHead = popped->_pNext; // Move the pHead to the next in queue
delete popped; // delete the popped value
--_itemCounter; // decrement counter
}
}
QueueItem.h
#pragma once
#include "Queue.h"
class QueueItem {
public:
QueueItem(const char* pData, int id); // ctor
void setNext(QueueItem* pItem);
QueueItem* getNext() const;
int getId() const;
const char* getData() const;
private:
char _data[30]; // data value (null terminated character string)
const int _itemId; // unique id for item in queue
QueueItem* _pNext; // next item in queue
};
In QueueItem.cpp below, the ctor is not right. The error C++ no instance of overloaded function matches the specified type comes up and I'm not sure why. It seems like the call matches the definition?
QueueItem.cpp
#include "QueueItem.h"
#include <cstring>
#include <string>
QueueItem::QueueItem(char* pData, int id) // ctor
: _itemId{ id } // Initialization list
{
strcpy_s(_data, pData);
_pNext = NULL;
}
void QueueItem::setNext(QueueItem* pItem)
{
_pNext = pItem;
}
QueueItem* QueueItem::getNext() const
{
return _pNext;
}
int QueueItem::getId() const
{
return _itemId;
}
const char* QueueItem::getData() const
{
return _data;
}
main.cpp
#include <iostream>
#include <conio.h>
#include "Queue.h"
using namespace std;
// note - you may need to change the definition of the main function to
// be consistent with what your C++ compiler expects.
int main() {
char anykey;
Queue myQueue;
myQueue.removeItem();
myQueue.addItem("red");
myQueue.addItem("green");
myQueue.addItem("blue");
myQueue.addItem("orange");
myQueue.print(); // print contents of queue (item ID and data)
myQueue.removeItem();
myQueue.removeItem();
myQueue.removeItem();
myQueue.removeItem();
myQueue.print();
myQueue.erase();
myQueue.addItem("olive");
myQueue.addItem("mauve");
myQueue.addItem("purple");
myQueue.print();
myQueue.erase();
myQueue.print();
cout << "Press any key...";
anykey = getch();
return 0;
}

Let's walk through this in order.
Queue.h
#pragma once
#include "QueueItem.h"
You don't actually use the definition of the QueueItem in this header, you only mention pointers to it. To have a pointer to a type (without ever dereferencing it - in the header, that is) - we just need to know the type exists.
So, you can replace the include with the forward declaration
class QueueItem;
And break the cycle between the two header files. (You will now need to include QueueItem.h in Queue.cpp though, because you actually do use it there).
You actually don't need to include Queue.h in QueueItem.h either, because it isn't used at all.
In Queue.cpp below, there are two places where I think the code should either be _pTail->_pNext or _pTail._pNext.
Yep, your first thought was correct.
If it's the ->, then I get C++ member (declared at line 21 of) is inaccessible
The word "inaccessible" tells us that the problem with _pTail->_pNext is that QueueItem::_pNext is declared private. Only methods of the QueueItem class (or friends) itself are allowed to access its private members.
You could add a friend declaration to QueueItem to let Queue have privileged access to its private parts. But, as you already have a public accessor, you can just write _pTail->getNext() instead.
but using the . gives C++ expression must have class type.
This is because only class (and struct, and union) objects have members. You have a pointer to a class object, so -> is the right choice. If it helps to remember, p->member is essentially the same as (*p).member ... it's just nicer to type.
In QueueItem.cpp below, the ctor is not right. The error C++ no instance of overloaded function matches the specified type comes up and I'm not sure why. It seems like the call matches the definition?
These two are not the same:
QueueItem(const char* pData, int id);
QueueItem::QueueItem( char* pData, int id) { ... }
I try to just copy & paste lines like this where possible - there's no benefit in doing more typing, with more opportunity for mistakes, and it's sometimes hard to see these simple errors when you know what you intended to write.

Related

Storing a string into a Queue, using seperate class definitions, C++

I am trying to store a string input (a math equation) into a Queue linked list. To add a character into the Queue, i need to access the Queue function "Enqueue( )" from inside a separate class: the "Calculate" class.
I keep getting error messages ("Queue': undeclared identifier") and ("QueObj": undeclared identifier).
My code mostly looks like this (removed most unrelated code):
#include <iostream>
#include <stdlib.h>
#include <string>
class Calculate // Convert from string to node
{
public:
double Calc(string text)
{
input = text; // math notation, user input sent from main()
/* error message here -> */ Queue queObj; // Queue object created to access Queue functions
/* error message here -> */ queObj.Enqueue(text); // Enqueues the notation into a Queue
};
private:
string input; // The input string for the math equation
};
class Queue
{
public:
void Enqueue(string queVal) // Enqueue definitions
{
// Enqueue instructions
};
void Dequeue() // Dequeue definitions
{
// Dequeue instructions
};
bool IsEmpty() // Queue size check
{
// Queue size check
};
private:
Node *head = NULL; // Pointer for start of queue (set to NULL)
Node *tail = NULL; // Pointer for end of queue (set to NULL)
friend class Calculate; // Friend class allows Calculate to access Queue private data
};
int main()
{
string Eq1 = "1 + 2"; // math equation
Calculate calcObj; // object to access calculate class functions and variables
calcObj.Calc(Eq1); // stores the equation into calculate class
return 0;
}
What is simply happening is that the class Queue is not visible to the class Calculate since the compiler (roughly speaking) reads and compiles code in top to bottom fashion. So the compiler is unaware that there exists a class named Queue while it is parsing the contents of the class Calculate.
There are two ways to make this work:
Put the class declarations at the top of all the class definitions. A class declaration looks as follows:
class Queue
{
public:
void Enqueue(string queVal); // Enqueue definitions
void Dequeue(); // Dequeue definitions
bool IsEmpty(); // Queue size check
private:
Node *head = NULL; // Pointer for start of queue (set to NULL)
Node *tail = NULL; // Pointer for end of queue (set to NULL)
friend class Calculate; // Friend class allows Calculate to access Queue private data
};
And then in the bottom, you can define all the functions as follows:
void Queue::Enqueue(string queval)
{
// Enqueue instructions
}
// rest of the functions
Create a header file with all such class declarations in it, and then include that header file. And then create a .cpp file with all the function definitions in it. While compiling the program, link both the object files (recommended option, since it is less cluttered and easily scalable).
Also, unrelated to the problem here, but you should ideally explicitly mention the return type of main as follows
int main()
This code might even not compile under newer C++ standards, because of not explicitly mentioning the return type of main.
Also, you don't need to use a semi-colon (;) after function definitions.
Lastly, format you code properly (specifically, don't use inconsistent indentations).

Friend classes need to include or forward declare c++?

I have been struggling with errors when trying to build a binary tree using a queue. The problem is what classes should include what files and how to reference objects from the other classes? I threw my files into an IDE in an attempt to pinpoint just what the problems are and the results are below. Currently my issue is that in the Queue.h file, treePtr "does not name a type". You can see the evolution of this problem here This question is different from other posts because the two classes are friend classes. This brings up the problem of circular dependencies. I have tried all sorts of combinations of including files and forward declaring but one combination causes one type of issue, and another creates different errors.
Here is the main class:
#include <cstdlib>
#include "Tree.cpp"
using namespace std;
int main() {
Tree tree;
tree.addTreeNode(5);
return 0;
}
Here is the Queue.h:
#ifndef QUEUE_H_
#define QUEUE_H_
class Tree; //Was instructed to put this here
class Queue {
friend class Tree;
private:
typedef struct node {
Tree::treePtr treeNode; //Here is the problem
node* next;
}* nodePtr;
nodePtr head;
nodePtr current;
public:
Queue();
virtual ~Queue();
void push(Tree::treePtr t); //Here is the problem
int pop();
void print();
};
#endif /* QUEUE_H_ */
This is Tree.h:
#ifndef TREE_H_
#define TREE_H_
#include "Queue.h" //Was instructed to put this here
class Tree {
friend class Queue;
private:
Queue q; //Edit: Most likely problem since Queue and Tree are friends
typedef struct tree {
int data;
tree* left;
tree* right;
}* treePtr;
treePtr root;
int numNodes;
public:
Tree();
virtual ~Tree();
void addTreeNode(int integer);
};
#endif /* TREE_H_ */
This is tree.cpp
#include <cstdlib>
#include <iostream>
#include "Tree.h"
using namespace std;
Tree::Tree() {
root = NULL;
numNodes = 0;
}
void Tree::addTreeNode(int integer) {
numNodes++;
treePtr t = new tree;
t->left = NULL;
t->right = NULL;
t->data = integer;
cout << "add root\n";
root = t;
q.push(t); //This is a problem
q.print();
}
Tree::~Tree() {
// TODO Auto-generated destructor stub
}
You have to compile Tree.cpp and (I suppose you have one) Queue.cpp separately, instead of including Tree.cpp in your main.cpp.
Forward declarations are fine for friending classes, even if you do so circular.
Put #include "Tree.h" in your Queue.cpp file, to let the compiler see the full declaration.
In main.cpp just put #include " Tree.h".
To get the final executable link all of the produced object files main.o(bj), Tree.o(bj) and Queue.o(bj).
See also [Why should I not include cpp files and instead use a header?] please.
As I've noticed now your actual problem is, you cannot access nested classes/structs from a forward declared class/struct as you're requiring with accessing treePtr from Queue (treePtr should be better named something like TreeNode or similar BTW).
You cannot make treePtr a private nested type in this case, it must be publicly visible.
A viable way is to put treePtr in a namespace internal_, that indicates it's not intended for usage outside the API.
Another viable way is to make Queue a template class, that accepts any type of tree or other kind of nodes. Since can't see any use case, why Queue needs to know about the internal specifications of tree (besides the trivial stuff like copying aso.), it's not really necessary to make Queue a friend class.
My best guess here is that the problem was that since the classes Queue and Tree were friends, and Tree had an instance of a Queue as a data member, there was some conflict when trying to include files and forward declare. By sharing data members with Queue, the Tree class shared an instantiation of a Queue object with the Queue class, so there was some inception sharing going on that was not obvious. #πάντα ῥεῖ suggested to make the Queue a template class so that it could accept objects of any type, without having to couple with the Tree (which was done so the Queue class would know what to do with treePtr objects). Making Queue a template class solved the problem because now the Tree class can have an instance of a Queue, and I can pass objects of type treePtr to the Queue without the Queue knowing anything about the Tree class before hand.

Using Linked-lists to implement a stack, debug assertion failed

I am currently working on implementing a stack data structure using linked lists in C++. I can compile everything fine up until the point I test my "stack.push" method when I receive a debug assertion failed error that I have no where near enough knowledge as to how to begin to fix it. I just started on here so I cannot post images apparently, but in short it says:
Debug Assertion Failed!
Program...ual studio 2013/....~
File:f:/dd/vctools/crt/crtw32/misc/dbgdel.cpp
Line: 52
Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse
and here are my codes: Stack.h
#ifndef _STACK_H
#define _STACK_H
#include "LList.h"
typedef int ItemType;
class Stack{
public:
Stack();
~Stack();
int size() { return size_; }
void push(ItemType x);
ItemType pop();
ItemType top() { return top_; }
private:
ItemType top_;
void copy(const Stack &source);
int size_;
LList items_;
};
#endif _STACK_H
stack.cpp:
#include "Stack.h"
Stack::Stack()
{
size_ = 0;
ItemType top_ = NULL;
}
void Stack::push(ItemType x)
{
items_.append(x);
size_ += 1;
ItemType top_ = x;
}
ItemType Stack::pop()
{
ItemType top_ = size_ - 1;
size_ -= 1;
return items_.pop();
}
Stack::~Stack()
{
items_.~items_();
}
The error occurs after writing test code that assigns a stack and then tries to push a number onto the stack.
Any help would be appreciated and I apologize if there are any formatting issues with my post.
There are several problems with your code:
Like mentioned in another answer, append will add the item at the end of the list (i.e., at the bottom from stack perspective) instead of at the top.
Your usage of top is inconsistent, you should decide what it means. Classically, top would hold or point to the last inserted element.
You have syntax issues and you're actually redeclaring a new local variable for top instead of using the class member.
You have memory corruption in the destructor when you explicitly call the contained list destructor.
You are a bit confused as to what append does. Append places a value (in this case an ItemType x) to the end of your stack, not the front. You then assign the top of the stack to the end of the stack, and you lose the pointers to the head of your list.
In fact, there are multiple things wrong now that I look at the rest of your code. I think you lack an understanding of what Linked Lists do, and you should go and read them yourself instead of me just dropping working code in my answer.

C++ Cannot Return Object From Function

I am trying to use the C++ "Clipper Library" (http://www.angusj.com/delphi/clipper.php), but when I try to return one of the objects from the clipper library from a function, it seems to become null or is altered somehow
Here is the function I wrote. The only relevant lines should be the last 3.
ClipperLib::PolyTree MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles)
{
// Make all of the triangles CW
for (auto& triangle : triangles)
{
triangle.makeClockwise();
}
// Set up the Clipper
ClipperLib::Clipper clipper;
// To take a union, add all the paths as "subject" paths
for (auto& triangle : triangles)
{
ClipperLib::Path triContour(3);
triContour[0] = convertGLMToClipperPoint(triangle.getVertex(0));
triContour[1] = convertGLMToClipperPoint(triangle.getVertex(1));
triContour[2] = convertGLMToClipperPoint(triangle.getVertex(2));
clipper.AddPath(triContour, ClipperLib::PolyType::ptSubject, true);
}
// Now get the PolyTree representing the contours
ClipperLib::PolyTree tree;
clipper.Execute(ClipperLib::ClipType::ctUnion, tree);
return tree;
}
When I call clipper.execute, it writes into the tree structure some contour information. It writes the correct information, and I've tested that it's correct. However, when I return the tree, it doesn't seem to copy anything, and the PolyTree that results from this function is empty.
I'm sure that there's nothing wrong with the library and that I'm just making a beginner c++ mistake here. Hopefully someone has an idea of what it might be.
Thanks!
edit: For reference, here is a documentation page for the polytree (http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Classes/PolyTree/_Body.htm)
edit: I thought the clipper library wasn't open source, but it is. Here is the code
typedef std::vector< IntPoint > Path;
typedef std::vector< Path > Paths;
class PolyNode;
typedef std::vector< PolyNode* > PolyNodes;
class PolyNode
{
public:
PolyNode();
Path Contour;
PolyNodes Childs;
PolyNode* Parent;
PolyNode* GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
unsigned Index; //node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode* GetNextSiblingUp() const;
void AddChild(PolyNode& child);
friend class Clipper; //to access Index
friend class ClipperOffset;
};
class PolyTree: public PolyNode
{
public:
~PolyTree(){Clear();};
PolyNode* GetFirst() const;
void Clear();
int Total() const;
private:
PolyNodes AllNodes;
friend class Clipper; //to access AllNodes
};
Before doing anything, make sure the following program works correctly:
int main()
{
PolyTree p1;
// fill PolyTree with some values that make sense (please add code to do this)
//...
PolyTree p2 = p1;
PolyTree p3;
p3 = p1;
}
That is basically what we want to test. If you can get this code to work (add the relevant headers and initializations necessary), then you can focus back on the function. If the code above doesn't work, then there is your answer.
You need to get the code above to produce the correct copy semantics, and even just important, when main() exits, no memory corruption occurs on the destruction of p1, p2, and p3.
So either you can fix the class to copy safely, or forget about it and live with a class that you have to handle very carefully and in limited situations (i.e. you can't reliably return copies of it as you're doing now).
For the record and combining all the responses in the lengthy discussion to the question.
Problems are:
The value returned is a local variable that goes out of scope. This invokes the PolyTree destructor
The PolyTree contains a vector of PolyNode * pointers. Those are allocated when clipper.Execute() is invoked.
However PolyTree::Clear() does delete the nodes... and Clear() is invoked by the destructor.
So within the function, the content is correct (allocated by Execute()), when passed outside, in the absence of copy constructors and operator=, the destructor of the local variable is invoked an the nodes are cleared, the result received outside of the function is empty.
The code for PolyTree::Clear()
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
Probably you should follow the pattern of Execute and define your function as:
void MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles,ClipperLib::PolyTree &tree)
Assuming you don't want to modify the (obviously badly designed) Clipper library, you can do it like I suggested in my comment:
// Make sure to have this at the top of your header file:
#include <memory>
std::unique_ptr<ClipperLib::PolyTree> MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles)
{
// Rest of your code...
std::unique_ptr<ClipperLib::PolyTree> tree(new ClipperLib::PolyTree);
clipper.Execute(ClipperLib::ClipType::ctUnion, *tree);
return tree;
}
Then, when calling your function:
std::unique_ptr<ClipperLib::PolyTree> tree(yourMeshHandler.trianglesToPolyTreeUnion(/*...*/);
// make use of tree...
Still, I would suggest opening a ticket (if there's a bug tracker) or contacting the library's author about this issue.
Is there already a solution for this problem? I am dealing with the same problem.
Still no luck. The polytree outputs only memory adres.
when using : qDebug()<< "child id " << polynode->Childs;
When we have 2 childs, the output in terminal is :
std::vector(0x55f30d2a91b0, 0x55f30d258480)
I hope someone knows how to solve this..
Your problem is in the third line from the bottom of trianglesToPolyTreeUnion. The tree you are creating is created on the stack and is only in scope within the function.
You should dynamically allocate the memory and return a pointer to the tree or make your tree object a class member so it is still within scope once the function returns.

I'm new to C++. Please Help me with the Linked List (What functions to add)?

DEAR All;
Hi, I'm just beginner to C++;
Please help me to understand:
What functions should be in the Linked list class ?
I think there should be overloaded operators << and >>;
Please help me to improve the code (style, errors, etc,)
Thanks for advance. Igal.
Edit:
This is only first stage, the next one will be (hopefully) with templates.
Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp);
MyNODE.h
// This is my first attempt to write linked list. Igal Spector, June 2010.
#include <iostream.h>
#include <assert.h>
//Forward Declaration of the classes:
class ListNode;
class TheLinkedlist;
// Definition of the node (WITH IMPLEMENTATION !!!, without test drive):
class ListNode{
friend class TheLinkedlist;
public:
// constructor:
ListNode(const int& value, ListNode *next= 0);
// note: no destructor, as this handled by TheLinkedList class.
// accessor: return data in the node.
// int Show() const {return theData;}
private:
int theData; //the Data
ListNode* theNext; //points to the next node in the list.
};
//Implementations:
//constructor:
inline ListNode::ListNode(const int &value,ListNode *next)
:theData(value),theNext(next){}
//end of ListNode class, now for the LL class:
class TheLinkedlist
{
public:
//constructors:
TheLinkedlist();
virtual ~TheLinkedlist();
// Accessors:
void InsertAtFront(const &);
void AppendAtBack(const &);
// void InOrderInsert(const &);
bool IsEmpty()const;//predicate function
void Print() const;
private:
ListNode * Head; //pointer to first node
ListNode * Tail; //pointer to last node.
};
//Implementation:
//Default constructor
inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {}
//Destructor
inline TheLinkedlist::~TheLinkedlist(){
if(!IsEmpty()){ //list is not empty
cout<<"\n\tDestroying Nodes"<<endl;
ListNode *currentPointer=Head, *tempPtr;
while(currentPointer != 0){ //Delete remaining Nodes.
tempPtr=currentPointer;
cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl;
currentPointer=currentPointer->theNext;
delete tempPtr;
}
Head=Tail = 0; //don't forget this, as it may be checked one day.
}
}
//Insert the Node to the beginning of the list:
void TheLinkedlist::InsertAtFront(const int& value){
ListNode *newPtr = new ListNode(value,Head);
assert(newPtr!=0);
if(IsEmpty()) //list is empty
Head = Tail = newPtr;
else { //list is NOT empty
newPtr->theNext = Head;
Head = newPtr;
}
}
//Insert the Node to the beginning of the list:
void TheLinkedlist::AppendAtBack(const int& value){
ListNode *newPtr = new ListNode(value, NULL);
assert(newPtr!=0);
if(IsEmpty()) //list is empty
Head = Tail = newPtr;
else { //list is NOT empty
Tail->theNext = newPtr;
Tail = newPtr;
}
}
//is the list empty?
inline bool TheLinkedlist::IsEmpty() const
{ return (Head == 0); }
// Display the contents of the list
void TheLinkedlist::Print()const{
if ( IsEmpty() ){
cout << "\n\t The list is empty!!"<<endl;
return;
}
ListNode *tempPTR = Head;
cout<<"\n\t The List is: ";
while ( tempPTR != 0 ){
cout<< tempPTR->theData <<" ";
tempPTR = tempPTR->theNext;
}
cout<<endl<<endl;
}
//////////////////////////////////////
The test Driver:
//Driver test for integer Linked List.
#include <iostream.h>
#include "MyNODE.h"
// main Driver
int main(){
cout<< "\n\t This is the test for integer LinkedList."<<endl;
const int arraySize=11,
ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12};
cout << "\n\tThe array is: "; //print the numbers.
for (int i=0;i<arraySize; i++)
cout<<ARRAY[i]<<", ";
TheLinkedlist list; //declare the list
for(int index=0;index<arraySize;index++)
list.AppendAtBack( ARRAY[index] );//create the list
cout<<endl<<endl;
list.Print(); //print the list
return 0; //end of the program.
}
What functions should be in the Linked list class ?
That depends on what you need to do with it. At the very least, one should probably be able to add elements to it, and to look at the elements in the list.
(This is common sense. Because if you can't modify or read your list in any way, what could it ever be used for?)
I think there should be overloaded operators << and >>;
Why? What would they do? I suppose you mean operator << to do insertion, similar to how objects are inserted into C++ IO streams; but what exactly should operator >> do? Extraction/removal of elements of some sort? If you implement insertion and extraction (?) in this manner, probably noone will be able to understand your linked list class. A linked list is not an IO stream. (Those operators with IO streams were chosen for brevity.)
I would advise you against operator overloading if the meaning of the operation is not clear. I would suggest you name your operations more explicitly, e.g. by providing methods add and remove (I'm still guessing at the meaning of the latter operation >> btw.).
Please help me to improve the code (style, errors, etc,)
I don't want to make this the main point on my answer, so just very briefly off the top of my head, some issues:
You should #include <iostream> instead of #include <iostream.h>, and then either add a using namespace std; or write (e.g.) std::cout instead of cout.
Try to get rid of the friend. You should be able to design your classes in a way that doesn't require this. friend is easily misused to get around proper encapsulation. But encapsulation is something you should definitely think about in OOP.
Though that's not an advice to give to a C++ beginner, if you made your linked list class into a template class, it could store different values than just ints. Just take this as a hint for future improvements.
And finally:
Just use the STL ("Standard Template Library") containers which are included in the C++ standard library. I know that "rolling your own" helps understanding how these data structures work, but be aware that the C++ standard library already includes a solid and efficient set of data containers.
0 should be NULL
inline only in the case that you don't care that your code will be public, usually implementation puts in separate file Mylist.cpp file.
Why your destructor virtual, do you have inheritance ?
You can just define struct node instead separate class its better define your list for practice like in stl. http://www.sgi.com/tech/stl/List.html http://www.cplusplus.com/reference/stl/list/
In C++ common to use vector vs linked list in Java
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html