The c++ constructor is a protected attribute, how to instantiate it

If a class's constructor is a protected property, an object of that class can be instantiated outside the class by:

1. Instantiation in the derived class: Since the derived class can access the protected members of the base class, the constructor of the base class can be called in the constructor of the derived class to create an object.

class BaseClass {
protected:
    BaseClass() {
        // 构造函数的实现
    }
};

class DerivedClass : public BaseClass {
public:
    DerivedClass() : BaseClass() {
        // DerivedClass 的构造函数可以调用 BaseClass 的构造函数
    }
};

int main() {
    DerivedClass derivedObject;  // 使用派生类来实例化对象
}

2. Use a factory function: You can write a static factory function in a friend of a class or in another class, which can access the protected constructor and return an instance of the class.

class MyClass {
protected:
    MyClass() {
        // 构造函数的实现
    }

public:
    static MyClass* createInstance() {
        return new MyClass();
    }
};

int main() {
    MyClass* myObject = MyClass::createInstance();  // 使用工厂函数来实例化对象
}

Note that the above methods all instantiate objects by bypassing protected access controls. Careful design and security considerations are required when using these methods, ensuring they are only used when necessary.

Guess you like

Origin blog.csdn.net/qq_26093511/article/details/131809389