can a class definition inside another class's definition

Discussion in 'C++' started by Jianli Shen, Mar 13, 2005.

  1. Jianli Shen

    Jianli Shen Guest

    Hi,

    I want to implement like this:

    class A{

    int length;

    class B{
    void operate_length_in_A(){
    length++;
    }

    void use_length_in_A(){
    if(length>8){
    }
    }

    B *Bobj;

    }

    because B will use member in A, so I think I can not put B ahead of
    definition of A.

    How can I do?

    Thanks
     
    Jianli Shen, Mar 13, 2005
    #1
    1. Advertising

  2. "Jianli Shen" <> wrote...
    > I want to implement like this:
    >
    > class A{
    >
    > int length;
    >
    > class B{
    > void operate_length_in_A(){
    > length++;
    > }
    >
    > void use_length_in_A(){
    > if(length>8){
    > }
    > }
    >
    > B *Bobj;
    >
    > }
    >
    > because B will use member in A, so I think I can not put B ahead of
    > definition of A.
    >
    > How can I do?


    Contrary to Java where a nested class is automatically instantiated as
    a member of the outer class and also gets all members of the outer class
    accessible and associated with the same instance of the outer class as
    the nested instance, in C++ a nested class definition is nothing but
    a definition of a type.

    If you need to access non-static data members of the outer class (like
    'length' in your example) from a function that is not a non-static member
    of that outer class, you would need an instance to go along with it:

    ...
    class B {
    void operate_length_in_A(A& a) {
    a.length++;
    }
    ...

    Where you put the definition of B inside A shouldn't matter.

    V
     
    Victor Bazarov, Mar 13, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. nail
    Replies:
    0
    Views:
    1,563
  2. Replies:
    1
    Views:
    2,712
    =?ISO-8859-1?Q?Stefan_N=E4we?=
    Jan 9, 2006
  3. =?ISO-8859-2?Q?Miros=B3aw?= Makowiecki

    Decralation of class inside other class and definition outside this class

    =?ISO-8859-2?Q?Miros=B3aw?= Makowiecki, Jul 13, 2007, in forum: C++
    Replies:
    2
    Views:
    344
    Alf P. Steinbach
    Jul 13, 2007
  4. Kiran More
    Replies:
    2
    Views:
    326
    Kiran More
    Nov 14, 2006
  5. 123Jim
    Replies:
    0
    Views:
    148
    123Jim
    May 16, 2011
Loading...

Share This Page