0

Im trying to link one display to another display using c++. For instance

void funcA(){
Display greenScreen; 
Display redScreen;

greenScreen.setChild(redScreen); 
}

Here's the class implementation:

class display{
public:
display* child = nullptr; 
void setChild(display);
}

Implementation of setChild:


void setChild(display childnode){
child = &childnode; 
}

I thought this would work, but when i tried to retrieve greenScreen's child, my app crashed. Any help would be greatly appreciated!

kiwiboy
  • 23
  • 3
  • 1
    Helpful reading: [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419) – user4581301 Jul 06 '21 at 06:40

1 Answers1

0

This is passing childnode by value: a copy is made, and you're setting this->child to the address of the copy. But the copy only lives while setChild is executing, so when it returns, you're left with a dangling pointer, causing undefined behaviour (probably crashing).

You must pass the address of childnode instead:

void setChild(display *childnode){
child = childnode; 
}
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 1
    Why not pass a display be reference and take its address internally. Prevents you accidentally setting it to null. Add an explicit function for decoupling displays. – Martin York Jul 06 '21 at 06:40
  • @MartinYork That's also possible, but a bit unconventional in my experience. Using a pointer has the advantage that you can see at the call site that a pointer is being passed, not a value. – Thomas Jul 06 '21 at 06:42
  • 1
    @Thomas But it also has a disadvantage that it is not clear whether a null pointer can be passed of not. – Evg Jul 06 '21 at 07:49
  • Hi guys, thank you so much for answering, i am sad to have overlook this detail. I have posted another thread on regards to gathering more opmitized solution for this problem. Do check out if you guys are interested! https://stackoverflow.com/questions/68268828/how-would-you-program-the-logic-of-gui – kiwiboy Jul 06 '21 at 10:27