Search code examples
c++c++11thisthis-pointer

Initialize a class object with the this pointer in C++


In C++, I want to initialize (or change) a class object using the result of another class' method. Can I use the this pointer? Is there a better way?

Dummy example:

class c_A {
    public:
    int a, b;

    void import(void);
};

class c_B {
    public:

    c_A create(void);
};

void c_A::import(void) {
    c_B B; 
    *this = B.create();
};

c_A c_B::create(void) {
    c_A A;
    A.a = A.b = 0;
    return A;
};

Solution

  • There is no problem. The member function void import(void); is not a constant function.In this statement

    *this = B.create();
    

    there is used the default copy assignment operator.

    Is there a better way?

    A better way is not to use a member function and just use an assignment statement for objects of the class as for example

    c_A c1 = { 10, 20 };
    
    c1 = c_B().create();