lundi 30 octobre 2023

C++ Class, the member object in the Class can be created using ’this‘ pointer outside the construct func?

#include<stdio.h>
#include <iostream>
class myClass;

struct Member
{
    Member(myClass* m)
    {
        std::cout << "member is created" << std::endl;
        my_class = m;
    }
    myClass* my_class;
};



class myClass
{
public:
    myClass()
    {
        std::cout << "myClass is created" << std::endl;
    }

    Member my_member =  Member(this);
    int x = 1;
};

void test() 
{
    myClass mClass;
    std::cout << mClass.my_member.my_class->my_member.my_class->my_member.my_class->x;
}

int main()
{
    test();
}

i define a Member Class, and it can construct with a myClass pointer. importantly, i define the my_member outside the myClass constructor, will it lead to recursive construction? the code above runs well, is it explainable? when does the 'this' pointer is created and can be used?

Aucun commentaire:

Enregistrer un commentaire