Normally, it is not possible to access a nested class if it is declared in private
section from outer scope:
#include <iostream>
#include <vector>
class Outer
{
private:
class Inner
{
public:
void sing() const { std::cout << "la la la\n"; }
void laugh() const { std::cout << "ha ha ha\n"; }
};
private:
std::vector<Inner> inners;
public:
void add() { inners.push_back(Inner()); }
};
int main()
{
auto o = Outer();
auto i = Outer::Inner(); // error: 'class Outer::Inner' is private within this context
}
However, with a small trick, the access is granted:
#include <iostream>
#include <vector>
class Outer
{
private:
class Inner
{
public:
void sing() const { std::cout << "la la la\n"; }
void laugh() const { std::cout << "ha ha ha\n"; }
};
private:
std::vector<Inner> inners;
public:
Inner & add() { inners.push_back(Inner()); return inners.back(); }
};
int main()
{
auto o = Outer();
auto i = o.add();
i.sing();
i.laugh();
}
Is the above valid C++ (11, 14, 17, etc.) or are just G++ (10.0.0) and Clang (10.0.0) playing tricks on me?
If this is valid, which rule allows this access?
Naively, I would assume that I cannot hold on to what Outer::add()
returns, or at best can hold it, but not access its members.