Just by curiosity, is it possible to declare a reference to an inner class in an outer class :
class A{
private:
class B{
public:
B(double val):val_(val){}
private:
double val_;
};
public:
A(double val):b(B(val)){} /*problem*/
private:
B& b;
};
int main(){
A a(1.0);
}
It feels logic that it is impossible because I don't see how one can assign a
reference to a temporary variable. But I'd like to be sure. (I would like to
use a ref rather than a pointer to guarantee the presence of a B
in A
.)
Edit
As I had the question why I'd like to do that, here is my goal. Let's imagine
that the class B
contains a lot of data and require a lot of memory. I don't
want to have many copy of B otherwise I will run out of memory. Now I have two
class C
and D
that both inherit of A
. I want them to be related to the
same instance of B
. I could do that with a pointer, but as said before I want
to make sure that at least a B
exists somewhere, so I though that by using a
ref I would be able to guarentee that. I also would like B
to be an inner
class so that I don't pollute my code. Thanks to your help, I now use a rvalue
reference and my code looks like this :
class A{
class B{
public:
B(double val):val_(val){}
private:
double val_;
};
public:
A(double val):b(B(val)){}
A(A const& a):b(a.b){}/*new problem*/
protected:
B&& b;
};
class C: public A{
public:
C(A const& a):A(a){}
};
class D: public A{
public:
D(A const& a):A(a){}
};
int main(){
A a(1.0);
C c(a);
D d(a);
}
but it doesn't compile.