Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneral programming question about scope
    text
    copied!<p>This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would greatly appreciate it.</p> <p>Let's say I have a class called A. In this class, I create an instance of a class called B:</p> <pre><code>class A { //instance variables classB; variable1; variable2; //instance methods instanceFunction(parameter1, parameter2) { //Do Stuff } function1(parameter1) { classB = new B(some parameters); } setVariable1(value) { variable1 = value; } getVariable2() { return variable2; } } </code></pre> <p>In class B, I want to make changes to or make use of instance variables in class A. I can do this by passing a reference to A into B. So my A::function1 would look like this:</p> <pre><code>function1(parameter1) { variable1 = new B(this, other parameters); //Python syntax: //variable1 = B(self, other parameters) } </code></pre> <p>and my class B would look like this:</p> <pre><code>class B { //instance variables parentClass; variable2; //instance methods instanceFunction(classA, other parameters) { parentClass = classA; } function1() { parentClass.setVariable1(someValue); } function2() { variable2 = parentClass.getVariable2(); } } </code></pre> <p>What other ways are there to have use of the variables in class A inside of class B?</p> <p>If the code was C++ or Java, assume all variables are private and all methods and functions are public. Also assume all variables are passed by references or a pointers.</p> <p>Edit:</p> <p>First, thanks for all the responses!</p> <p>Some clarification: </p> <p>The reason I am asking this question is I have done a good amount of Qt programming in C++ and Python. In Qt, there are signals and slots. This lets inner objects tell the outer object to do something. For example I have an object A with objects B and C inside of it. Some change happens to object B and B needs to let A and C know. So B will emit a signal. A will catch this signal and do what it needs to do. Then, A will also let C know that B emitted this signal. This way C can do what it needs to do.</p> <p>The reason I asked my question is because I was wondering how I can do something like I described without using the Qt libraries.</p> <p>Also, let's assume B "is not" an A so I can't/don't want to use inheritance. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload