Reputation: 67
So I'm just playing around and created a simple class:
class C {
public:
C() {
}
void assign() {
*a = 10;
}
int * get() {
return a;
}
private:
int *a;
};
Then I create an instance of the class as follows:
C c{};
c.assign();
For some reason, the method assign doesn't actually get called.
std::cout << c.get() << std::endl;
This returns nothing in the console.
Upvotes: 0
Views: 173
Reputation: 2080
You are causing an undefined behaviour by derefercing unallocated memory , You should add this to your class
C()
{
a=new int;
}
and
~C()
{
delete a;
}
Upvotes: 3
Reputation: 1409
The problem with your code is your are derefrencing the unintialized pointer varibale. To accomplished the same you have to initialize your a
pointer variable. You can acoomplish the same with this code.
class C {
public:
C() :a(new int){
}
void assign() {
*a =10;
}
int* get() {
return a;
}
~C() {
delete a;
}
private:
int* a;
};
Upvotes: 0