C++: Can a class has an object of it's own type?

3.2k views Asked by At

I am trying to solve the Conway's game of life in c++. So according to my design, I have a cell class which contains a list of 8 neighbours, which itself is an object of type cell. Is it ok to do that. The code looks like this

class Cell {
private:
  int position_row_;
  int position_colm_;
  std::shared_ptr<State> state_;

  std::vector<Cell> neighbours_;
};

Now, the other question that is bugging me is, what type of relationship is it. While designing i thought of it to be 'Aggregation'; but now i don't think so. Can someone please clarify?

3

There are 3 answers

4
rockoder On BEST ANSWER
std::vector<Cell> neighbours;

You are storing copy of neighbours. What if state of any neighbour changes? Do you need that change to be reflected into the vector? If yes, better store the pointers to the neighbours:

std::vector<std::shared_ptr<Cell>> neighbours;
1
Sanders On

A class cannot include itself as a data member class C { C c; }; for two reasons:

  1. When you try to define the data member the class is still an incomplete type.
  2. You are creating an endless chain of objects which would require infinite memory.

A class can contain a vector of itself class C { std::vector<C> vec; }; because, like a pointer, a vector declaration only requires that data type has been declared - not defined.

Your code will compile and run but you said your intent was for aggregation which isn't the case:

  • Your code std::vector<Cell> neighbours; is a case of composition because the objects in the vector are owned by the Cell object.
  • Using pointers to other Cell objects std::vector<Cell*> neighbours; would be a case of aggregation because the Cell object would use the objects in the vector but not own them.
0
Bupa On

This is considered to be Reflexive Association. Because it is satisfying following conditions with having its own type has a member variable

The associated object (member) is otherwise unrelated to the object (class)
The associated object (member) can belong to more than one object (class) at a time
The associated object (member) does not have its existence managed by the object (class)

This can lead to a chain of associations The associated object (member) may or may not know about the existence of the object (class)