So I have concerns about accessing a class from within a class. The pseudocode below is not identical but is similar to the structure I have.
class Parent{
constructor(name, children){
this.name = name
this.children = children;
}
AddChild(Child){
this.children.push(Child);
}
RemoveChild(Child){
this.children = this.children.filter(child => child != Child);
}
}
class Child{
constructor(name, age){
this.name = name;
this.age = age;
}
cycle(){
setInterval(() => {
if(this.age >= 18){
//Remove this child from parent
}
this.age ;
}, 10000);
}
}
For this example, I need to remove child
from parent
when the child is above the age of 18. However, I cannot access the parent from within the Child. I have tried referancing the parent as a property of child but have never used circular referancing before and dont know how safe it is to do so.
My questions are as follows:
- For this example, what is a way of accessing the parent function
RemoveChild()
from the child class. - Is circular referancing a safe partise to use for this example.
CodePudding user response:
In your axample, as you pointed out, you for sure need a reference to the Parent
in the Child
class, otherwise you cannot call a method of it, because you don't have an instance of it.
About circular references, you also pointed out that it can be something dangerous. If a Child
can live without a Parent
, you should always check when accessing its parent field that is a set to a value (not null).
The biggest problem about circular references are memory leaks. A garbage collector (for language having one, such as JS) or a smart pointer (for languages like C or Rust, not having garbage collection) basically looks if the object is still referenced somewhere to know when to free its memory. If a Parent
references a Child
and vice-versa, but nowhere else any variable references them, they are left alone in the wild, being never freed because each one of them is referenced by the other, but any other place doesn't. So you cannot access and use them anymore, but your program still has the memory allocated for them. Memory leaks can make a computer run out of memory on the long term. This is the main danger to care about.