I have been playing around with inner classes in C++
, and I'm bit confused right now.
My Code:
#include <iostream>
class outer{
private:
class inner{
private:
int something;
public:
void print(){
std::cout<< "i am inner"<<std::endl;
}
};
public:
inner returnInner(){
inner i;
return i;
}
};
int main(){
outer o;
//outer::inner i = o.returnInner(); (1)
//auto i = o.returnInner(); (2)
//i.print();
o.returnInner().print(); //(3)
return 0;
}
This is compiled on Linux with clang++-3.5
and -std=c++14
.
In (1) I'm getting a compiler error as expected because
inner
is a private inner class ofouter
.However, in (2) when the
auto
keyword is used, compilation is successful and the program runs.Everything works for (3), too.
My question:
Why is this so? Can I prevent returning an instance of private inner class from outer methods while retaining the ability to move and/or copy them within the outer class?
Shouldn't the compiler elicit an error in (2) and (3) like it does in (1)?