The following situation:
class Main{
void MainMethod(){
C * c;
B * b = new B();
b->fillC(c);
}
};
class B{
void fillC(C* c){
c = new C();
}
};
class C{
};
In my software I have this situation. At the end of the program c is still empty for class Main. Why is this?
The pointer
cis copied into thefillCfunction – this is known as passing by value. You then assign to that copy. The originalcvariable fromMainMethodis left unaffected. You need to pass the pointer by reference if you want to change it:Now the
cinsidefillCrefers to the same pointer as thecinMainMethod. Changing the value of one affects the value of the other.You could alternatively change the parameter of
fillCto typeC**, call it withfillC(&c)and assign to it with*c = new C()– but you’re already using a mishmash of idioms from other languages, so I wouldn’t recommend this.Don’t forget to do
delete cat some point!