0

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;
};
Medical physicist
  • 2,510
  • 4
  • 34
  • 51

1 Answers1

2

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();
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335