0

I know that is possible for a struct:

struct A{
    A* p;
};

But could we do that to a class:

class B{
    B*p;
}

I tried to google it, but end not found it. Thank you very much!

heLomaN
  • 1,634
  • 2
  • 22
  • 33
  • 5
    @ShafikYaghmour and Dani: Just trying it out works badly in C and C++, because of the large number of things which invoke undefined behavior (and are hence broken), yet appear to work fine in most (especially naive) experiments. That is not to say this is a good question, but it should not be resolved by simply trying it. –  Mar 02 '14 at 15:57
  • There is a difference in the two declarations. A* is public and B* is private – Abhishek Bansal Mar 02 '14 at 15:57
  • @Dani: Finding out the properties according to the standard of C++ by throwing code at a compiler and seeing what sticks is often quite dangerous. – Lars Viklund Mar 02 '14 at 15:57
  • Oh Thank you very much for reminding. I forgot to try the code. Very sorry about that. – heLomaN Mar 02 '14 at 15:59
  • @delnan this is basic question and it is not asking is this valid or something similar but does it work, which seems off-topic but I commented in case I was missing something. – Shafik Yaghmour Mar 02 '14 at 15:59
  • 1
    @ShafikYaghmour "Works" encompasses (or at least *should* encompass) "has defined behavior"; code with UB is worse than a compiler error or consistently-wrong output as it breaks unexpectedly and in very confusing ways. –  Mar 02 '14 at 16:02
  • Note that you have class *definitions* there. – juanchopanza Mar 02 '14 at 16:12

2 Answers2

4

Yes. There is no difference between a class declared with struct and one declared with class other than the default access for members and bases.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
1

Yes, a class can contain pointers to a class of the same type, and the symbol representing the class can appear in signatures of functions or in the bodies of functions defined in that class. Furthermore, it should be noted that, in C++, struct and class are identical with only one difference -- the default access level for a struct is "public", while the default access level for a class is "private" (of course, one can trivially write "public:" or "private:" at the beginning of either in order to change the access level; it is only convention that results in "class" being used for types that include more functionality, encapsulation and "struct" for pure data objects).

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200