schumacher574 schumacher574 - 3 months ago 7
C++ Question

Where to define struct only to be used as private member variable?

Take the following header file example, where Bar is a struct:

class Foo
{
...
private:
Bar _bar;
};


I only want
Bar
to be accessible as a private member variable for
Foo
. What is the proper way to declare and define
Bar
?

Option 1: define in header?

I'd like to avoid this, as I don't want
Bar
to be usable outside the
Foo
class scope.

struct Bar
{
int a;
int b;
...
};

class Foo
{
...
private:
Bar _bar;
};


Option 2: forward declare in header, define in cpp?

Not sure if this is legal, as how will the compiler know the size of
Foo
strictly from the header if
Bar
's definition isn't directly available? Also, will this hide
Bar
from other files that include the header?

header:

struct Bar;

class Foo
{
...
private:
Bar _bar;
};


implementation file:

struct Bar
{
int a;
int b;
...
};


Option 3: declare within class

Maybe the best option to limit scope, but potentially messy?

class Foo
{
...
private:
struct Bar
{
int a;
int b;
...
};

Bar _bar;
};

Answer

For the option 2 to compile, _bar should be a pointer. Option 3 is best, since it doesn't pollute namespace.

Comments