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;
};