Right way to conditionally initialize a C++ member variable?

前端 未结 6 1129
执念已碎
执念已碎 2020-12-30 07:18

I\'m sure this is a really simple question. The following code shows what I\'m trying to do:

class MemberClass {
public:
    MemberClass(int abc){ }
};

clas         


        
6条回答
  •  感动是毒
    2020-12-30 07:54

    To have the initialization happen after other stuff happens, you do indeed need to use pointers, something like this:

    class MyClass {
    public:
        MemberClass * m_pClass;
        MyClass(int xyz) {
            do_something(); // this must happen before m_class is created
            if(xyz == 42)
                m_pClass = new MemberClass(12);
            else
                m_pClass = new MemberClass(32);
        }
    };
    

    The only difference is that you'll need to access member variables as m_pClass->counter instead of m_class.counter, and delete m_pClass in the destructor.

提交回复
热议问题