Is it possible that a class attribute is the class itself?

Asked

Viewed 137 times

4

I’m starting to learn C++ Object oriented, and I have to make an algorithm using chained lists. In C, I used a structure that had as one of the attributes a pointer to the structure itself. I wonder if it is possible to do something similar to the C++, but using classes instead of structures.

Follow 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

};
  • 1

    Are you having any problems? Not only is it possible, but chained lists are assembled anyway. Of course it needs some care not to create a dependency on creation that creates a loop infinite, but it’s rare to be able to do that.

  • Actually, I don’t know practically anything about C++, so my fear of doing so. My intuition said that was it, but I wanted to be sure. Thanks for the help!

2 answers

4


In C++ it is possible that an attribute of a class is the class itself? NAY.

In C++ it is possible that an attribute of a class is A POINTER to the class itself? YES.

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

Tip: In class names, start with uppercase. It’s a convention that virtually 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
};
  • Yeah, that pointer detail went unnoticed, I forgot to emphasize that. And on the class name, that was an oversight, I usually do that. Thanks for the tips

0

I came to do a similar college job, I had done a program with a structure with a pointer to the structure itself, but then I had to do one in tree and using classes. The only thing that changed is that I had two pointers to the class itself.

  • Creating a pointer to the class itself you are just creating a path to a particular memory address, not necessarily this address will be filled in.
  • You can declare a class with a pointer to the class itself and then build new class as needed, so you would create your chained list.
  • Ah, ok. I was just afraid I didn’t really know the language yet, but if that’s it, better. Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.