There are two watertight containers inside of class A
: double c
and struct Controller
. From inside of one you cannot get to the other. The rule in C++ layers of abstraction is that you cannot go from the inside out. You can only go from the outside in. Controller::fire()
can only see stuff inside the Controller
itself. It has no knowledge of the outside world.
You can improve your code by getting rid of the Controller
all together. It is a "wall" which prevents your function from seeing the double c
because it is sitting inside that wall:
#pragma once
using namespace std;
class A {
public:
double c;
double fire () { return c * 2};
A();
};
The other way to do it would be to provide some "door" through the "wall", some kind of mechanism to get the double c
into the Controller
to make it visible to the double fire()
. I mean declare a constructor Controller::Controller()
and pass a pointer in.
#pragma once
using namespace std;
class A {
public:
double c;
struct Controller {
Controller(double* ptr) : c_ptr(ptr) {}
double * c_ptr;
double fire () { return *c_ptr * 2};
};
Controller control(&c);
A();
};
As mentioned in another answer, you can also use references in C++. That would actually be even better in this situation.
#pragma once
using namespace std;
class A {
public:
double c;
struct Controller {
Controller(double& input) : c(input) {}
double& c;
double fire () { return c * 2};
};
Controller control(c);
A();
};