Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use class which defined below?

Tags:

c++

class

class A{
 public:
 B b;
};

class B{
 public:
 A a;
};

I can't write in A class "B b" because class B defined below. Is any way to make it work?

thanks

like image 626
VextoR Avatar asked Dec 08 '25 01:12

VextoR


2 Answers

This is not possible. You need to use a pointer or a reference in one of the classes.

class B; // forward declare class B
class A {
public:
  B * b;
};

class B {
public:
  A a;
};

As to why it isn't possible: A contains a B contains an A contains a B ... There's no end to the recursion.

If you're used to languages (such as e.g. java) where all object variables are pointers/references by default, note that this is not the case in c++. When you write class A { public: B b; }; a complete B is embedded into A, it is not referred to within A. In C++ you need to explicitly indicate that you want a reference (B & b;) or a pointer (B * b;)

like image 116
Erik Avatar answered Dec 10 '25 15:12

Erik


Think about it: Inside an object of class B there's an object of class A, and inside it there's an object of class B. This is physically impossible! What will be the size of object B?

sizeof(B) > sizeof(A) > sizeof(B)

You must use pointers, like the other answer suggested.

like image 20
Ilya Kogan Avatar answered Dec 10 '25 14:12

Ilya Kogan



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!