Tim
Tim

Reputation: 67

Unable to assign a class member pointer variable

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

Answers (2)

Spinkoo
Spinkoo

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

foragerDev
foragerDev

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

Related Questions