Search code examples
c++classexplicit

Including a class requiring a input argument to its constructor in another class


I have a third party libary which defines a class as follows

class ClassA{
    
public:
    explicit(std::string token) : _token(token);
    
    inline const std::string& getToken() const{
        return _token;
    }
    
    // Other functions
    // ...

private:
    const std::string _token;
    // other members
    // ...
};

I am trying to make the class a member of an another class. However, since ClassA requires the constructor with an input argument, is there a workaround to define another class that gets the token and creates an object?

class ClassB{
    ClassB(std::string token) : m_TOKEN(token){ setBot(); };
    
    void setBot(){
        m_classA(m_TOKEN); // I know this does not work, it is just to illustrate my question.
    };
    
private:
    std::string m_TOKEN;
    ClassA m_classA;    
}

Solution

  • As written, your ClassB will not work, as ClassA does not have a default constructor, so you will have to initialize m_classA in the member initialization list of ClassB's constructor. If you want setBot() to reset m_ClassA, it will have to construct a new ClassA object.

    class ClassB{
        ClassB(std::string token) : m_TOKEN(token), m_classA(token) { };
        
        void setBot(){
            m_classA = ClassA(m_TOKEN);
        };
        
    private:
        std::string m_TOKEN;
        ClassA m_classA;
    }
    

    Otherwise, if you don't want to initialize m_ClassA in the consturctor's member initialization list, then you will have to construct m_ClassA dynamically instead.

    class ClassB{
        ClassB(std::string token) : m_TOKEN(token) { setBot(); };
        
        void setBot(){
            m_classA = std::make_unique<ClassA>(m_TOKEN);
        };
        
    private:
        std::string m_TOKEN;
        std::unique_ptr<ClassA> m_classA;    
    }