Reputation: 823
Here is my 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 a result,I didn't see anything printed out. I know that f1 & f2 are not created actually. So I'm wondering if I can instantiate a class like this? If yes, then how ?
Upvotes: 0
Views: 575
Reputation: 16328
You need to pass the pointer by reference.
void createForm(form* &f,int c){
f = new Form(c);
}
However, I would rather change the createForm
function to look like this:
form* createForm(int c) {
return new Form(c);
}
Upvotes: 5
Reputation: 258618
void createForm(form* f,int c){
f = new Form(c);
}
will create an object and assign its address to the local f
- which is a copy of the original f1
and f2
withing that function's scope.
The original pointers are left unchanged, so the following cout<<
statements lead to undefined behavior.
What you're trying to achieve can be accomplished by passing the pointer by reference:
createForm(form*& f,int c)
You also forgot to call delete
, so now you have a memory leak.
Even better - don't use pointers at all.
Upvotes: 6