I’m learning C++ (coming from Java) and this is bugging the hell out of me, say I have…
class Foo {
public:
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
Bar *y; // <- This is a pointer, Bar is not instantiated (this is just another placeholder)
Bar z; // <- What is this???
};
class Bar {
public:
Bar(int bunchOfCrap, int thatNeedsToBeHere, double toMakeABar);
};
In this example Bar has one constructor that needs a bunch of fields specified in order to create a “Bar.” Neither x, nor y creates a Bar, I understand that x creates a reference that can be pointed to a Bar and that y creates a pointer that can also represent a Bar.
What I don’t understand is what exactly z is.
-
Is it a Bar? And if so, how can it be given Bar’s only constructor?
-
Is it a Bar sized chunk of memory belonging to instances of Foo that can be initialized into a Bar?
-
Or is it something else?
Thanks!
For pedagogical reasons, let’s try to compile this code:
Output:
As it says, you must initialize both the member reference
Bar &xand the member variableBar z;, becauseBardoesn’t have a default constructor.ydoesn’t have to be initialized, and it will default toNULL.Both
xandyindirectly refer to the object. You can’t change whatxrefers to (so it must be initialized whenFoois instantiated). You can change whatyrefers to.zis aBar-sized chunk of memory which lives insideFoo; for you to legally declare a member variable like this, you have to put the complete definition ofBarbeforeFooso that the compiler knows how bigBaris.