C++ : behavior between initialization list and constructor body

166 views Asked by At

What is the difference between those two variants? They seem to behave in exactly the same way.

class A{
public:
    A():b(nullptr)
        {
            b = this; // variant 1
            b.a = this; // variant 2
        }
    class B {
    public:
        B(A* a):
            a(a){}
    private:
        friend class A;
        A* a;
    };
    B b;
};
1

There are 1 answers

0
Michael On

First variant uses the implicit constructor, meaning that b is rebuilt using the this pointer. Second variation simply modifies the value of b.a. Note that in this simple implementation there is no difference.