Kiran
Kiran

Reputation: 63

Nested class in C++

I have

class outer: public base
{
public:
 class inner
 {
   foo();
 }
}
  1. How do i initialize these nested class?
  2. Can I call foo() from the outer class?
  3. Can you please tell me what is the thumb rule I should know while nesting class and accessing the members? Thank you

Upvotes: 2

Views: 856

Answers (2)

sehe
sehe

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

  1. How do i initialize these nested class?

You don't. You can only initialize members (class instances)

  1. Can I call foo() from the outer class?

Not unless you are a friend or the method (foo()) is public

  1. 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

  1. the type is an implementation detail or depends on the outer class
  2. the convenience of sharing static members (enums, typedefs, template arguments, static methods and fields) from the outer class: the inner class is implicitly a friend of the outer class.

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

Damir
Damir

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

Related Questions