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?
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.
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.
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.
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 .
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With