Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 839
divine-code Avatar asked Oct 31 '25 04:10

divine-code


1 Answers

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.
like image 132
Sanders Avatar answered Nov 02 '25 19:11

Sanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!