user782311
user782311

Reputation: 961

How to define a class within another class' private in C++

Is it possible to define a class in another classes private and use it for an array? For instance:

class a
{
    public:
    private:
    class b;
    b myarray[10];

    class b
    {
        public:
        b(int a):a_val (a){}
        private:
        int a_val;
    };
};

Ignoring public, is there anything wrong with my syntax?

Is it also possible to make a member function in A to modify the private values of b. For instance, myarray[0].a_val = 5; If so, is this syntax also correct?

Upvotes: 8

Views: 20158

Answers (4)

pmr
pmr

Reputation: 59811

No, your syntax for defining a private nested class is alright. Although some other things are wrong: You need to define b before creating an array to it. The type needs to be complete.

b is not default constructible so you also need to initialize the array in a constructor initializer list, which is actually not possible in C++03. C++11 offers initializer lists to get that functionality.

Just use a std::vector or std::array.

Fixed version of your code:

class a
{
public:
  // ATTN C++11 feature here
  a() : myarray({ 1, 2}) {}
private:
  class b {
  public:
    b(int a) : a_val (a){}
    int a_val;
  };
  b myarray[2];
};
int main ()
{
  a a;
}

Upvotes: 7

Kerrek SB
Kerrek SB

Reputation: 476930

Yes, that's fine, but you have to define the nested class fully before declaring an array of it: Arrays can only be made of complete types:

class Outer
{
    class Inner { /* define it! */ };
    Inner a[100];
};

Upvotes: 2

John Humphreys
John Humphreys

Reputation: 39224

No, it's completely fine. It just means you can only declare instances of b within class a, which will stop people from doing:

a::b myB;

to declare their own b, which is presumably what you want.

Upvotes: 0

Yes you can declare classes privately inside other classes.

Yes, you can use them as the type of an array provided the class itself is visible to you where you create the array.

Upvotes: 0

Related Questions