This is really starting to confuse the hell out of me. When do I use them, when don’t I?
For example I was reading a .cpp on linked lists whose class declaration was:
struct CarPart
{
long PartNumber;
char Partname[40];
double UnitPrice;
CarPart *next;
};
class ListOfParts
{
int size;
public:
CarPart *head;
ListOfParts();
~ListOfParts();
const int count() const;
void insert( CarPart *item );
CarPart *retrieve( int pos );
};
With this code, why am I allowed to write
ListOfParts *pPart = new ListOfParts();
CarPart *pCarPart = new CarPart;
Declaring an instance of ListOfParts requires (), but not my CarPart? That’s confusing me. When I asked a question before and people told me that such a declaration is a function that returns a ListOfParts object, but not the actual constructor. So I’m guessing this is still something different.
What’s happening here?
PS: Am I correct to assume that the const to the right of count() means I cannot modify any values in count?
Declaring an instance of
ListOfPartsclass does not require()when allocating on the heap. Both forms are valid:EDIT: As the commenters have pointed out, it makes a difference when initialising a POD type (however is’s not relevant to your code sample).
However, when declaring a stack variable or a static variable, it matters, because the form with
()is the same as declaring a function.constto the right ofcount()means you cannot modify any values inside the current object in this function, which will bethis->sizeandthis->head(note, you can still change object pointed to byhead).