Chengkun Li
Chengkun Li

Reputation: 133

Can I instantiate a new object of current class in the class definition

#include <iostream>

class A
{
 public:
    A(int n = 1) : i(n) {}

    void Transform(int j)
    {
        // I want to create a new object and assign that object to "this"
        A *obj = new A(j);
        delete this;
        this = obj;
    }
private:
    int i;

};

Can I instantiate a new object of class A inside the function Transform() of class A and assign the new object to this while deleting the old object represented by this?

Upvotes: 3

Views: 217

Answers (3)

bartop
bartop

Reputation: 10315

This is not a valid C++ code, yet I think there is a simple way to achieve what You want:

#include <iostream>

class A
{
 public:
    A(int n = 1) : i(n) {}

    void Transform(int j)
    {
        *this = A(j);
    }
private:
    int i;

};

Upvotes: 0

jfMR
jfMR

Reputation: 24738

You can't assign to this, but you can still swap the object represented by this with a local object created in A::Transform():

#include <iostream>

class A
{
 public:
    A(int n = 1) : i(n) {}

    void Transform(int j)
    {
        A obj(j); // create a new object A
        std::swap(*this, obj);
    }
private:
    int i;

};

Upvotes: 2

llllllllll
llllllllll

Reputation: 16404

No, you can't. Because this is an rvalue pointer, which can't be assigned.

cppreference

The keyword this is a prvalue expression whose value is the address of the object

Upvotes: 0

Related Questions