class - C++ instantiation via pointer -


here code :

#include <iostream> using namespace std; class form{ public:     form(int c ){         code = c;     }     int code; }; void createform(form* f,int c){     f = new form(c); } int main(){     form* f1;     form* f2;     createform(f1,1111);     createform(f2,2222);     cout<<f1->code<<endl;     cout<<f2->code<<endl;     return 0; } 

as result,i didn't see printed out. know f1 & f2 not created actually. i'm wondering if can instantiate class this? if yes, how ?

void createform(form* f,int c){     f = new form(c); } 

will create object , assign address local f - copy of original f1 , f2 withing function's scope.

the original pointers left unchanged, following cout<< statements lead undefined behavior.

what you're trying achieve can accomplished passing pointer reference:

createform(form*& f,int c) 

you forgot call delete, have memory leak.

even better - don't use pointers @ all.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -