Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 692
user782311 Avatar asked Jan 24 '12 23:01

user782311


People also ask

Can we declare a class in another class?

A class can be declared within the scope of another class. Such a class is called a "nested class." Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope.

How do you make a private class member accessible in a different class?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

Can another class access private members?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

How do you call a class inside another class in CPP?

A nested class may inherit from private members of its enclosing class. The following example demonstrates this: class A { private: class B { }; B *z; class C : private B { private: B y; // A::B y2; C *x; // A::C *x2; }; }; The nested class A::C inherits from A::B .


1 Answers

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;
}
like image 83
pmr Avatar answered Sep 22 '22 12:09

pmr