Is it possible for an attribute of a class to be the class itself?

4

I'm starting to learn% object-oriented%, and I have to do an algorithm using threaded lists. In C++ , I used a structure that had as one of the attributes a pointer to the structure itself. I would like to know if it is possible to do something like C , but using classes instead of structures.

Here is an example of what I intend to do:

class item {
public:
    item(int profit, item *next);
    ~item();

    insertItem(int profit, item *ptList);

    returnItem(int i, int w, int W, item *ptList);//Função que retorna o objeto de uma matriz simulada com lista encadeada

private:
    int profit;//Valor correspondente ao objeto
    item *next;//Ponteiro para o próximo item da lista

};
    
asked by anonymous 23.09.2016 / 16:17

2 answers

4

In C ++ is it possible for an attribute of a class to be the class itself? NO .

In C ++ is it possible for an attribute of a class to be a POINTER for the class itself? SIM .

Detail: In C ++ a C structure is also considered as a class.

Tip: In class names, start with uppercase. It's a convention that pretty much everyone uses.

class Item
{
public:
    Item(int profit, Item* next);
    ~Item();

    void insertItem(int profit, Item* ptList);

    // nao consegui entender isso, acho que e' isso que voce quer
    Item* returnItem(int i, int w, int W, Item *ptList);

private:
    int profit; // Valor correspondente ao objeto
    Item* next; // Ponteiro para o próximo item da lista
};
    
23.09.2016 / 16:52
0

I even made a work for college similar, I had made a program with a structure with a pointer to the structure itself, but then I had to make a tree and using classes. The only thing that changed was that I had two pointers to the class itself.

  • Creating a pointer to the class itself is only creating a path to a particular memory address, not necessarily this address will be filled.
  • You can declare a class with a pointer to the class itself and then build new classes as needed, so you would create your linked list.
23.09.2016 / 16:24