Reputation: 63
I have
class outer: public base
{
public:
class inner
{
foo();
}
}
Upvotes: 2
Views: 856
Reputation: 392833
I guess you're coming from java.
A c++ nested struct/class is like a java static
nested type. It has no instance-relation with the containing type.
In fact you should be able to move the inner class to the containing namespace with no other changes than the potential need to mark the former inner class as a friend of the outer class.
See for demonstration http://ideone.com/ddjGX
- How do i initialize these nested class?
You don't. You can only initialize members (class instances)
- Can I call foo() from the outer class?
Not unless you are a friend or the method (foo()) is public
- Can you please tell me what is the thumb rule I should know while nesting class and accessing the members?
I'd choose a nested type only if
I illustrated these 'rules of thumb' below. Note how the nested type has transparent access to private members of the outer class.
struct base {};
class outer: public base
{
private:
enum { some=42, special=67, implementation=999, details=-13 };
public:
struct inner
{
protected:
void foo() { int can_usethis = special + implementation + details; }
};
outer() : _inner() { }
void call_inner(inner& i) const
{
//i.foo(); // fails (protected)
}
void call_inner() const
{
//_inner.foo(); // fails (protected)
}
private:
inner _inner;
};
int main()
{
outer o;
outer::inner i;
// i.foo(); // fails: protected
o.call_inner(i);
}
Upvotes: 6
Reputation: 56179
You can instance inner object using scope operator :: (outer::inner()) . If you want to acceess foo() from outer class you maybe want to define outer like friend class of inner.
Upvotes: 1