Can I call a constructor from another constructor (do constructor chaining) in C++?

前端 未结 15 2341
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
15条回答
  •  故里飘歌
    2020-11-22 01:46

    I would propose the use of a private friend method which implements the application logic of the constructor and is the called by the various constructors. Here is an example:

    Assume we have a class called StreamArrayReader with some private fields:

    private:
        istream * in;
          // More private fields
    

    And we want to define the two constructors:

    public:
        StreamArrayReader(istream * in_stream);
        StreamArrayReader(char * filepath);
        // More constructors...
    

    Where the second one simply makes use of the first one (and of course we don't want to duplicate the implementation of the former). Ideally, one would like to do something like:

    StreamArrayReader::StreamArrayReader(istream * in_stream){
        // Implementation
    }
    
    StreamArrayReader::StreamArrayReader(char * filepath) {
        ifstream instream;
        instream.open(filepath);
        StreamArrayReader(&instream);
        instream.close();
    }
    

    However, this is not allowed in C++. For that reason, we may define a private friend method as follows which implements what the first constructor is supposed to do:

    private:
      friend void init_stream_array_reader(StreamArrayReader *o, istream * is);
    

    Now this method (because it's a friend) has access to the private fields of o. Then, the first constructor becomes:

    StreamArrayReader::StreamArrayReader(istream * is) {
        init_stream_array_reader(this, is);
    }
    

    Note that this does not create multiple copies for the newly created copies. The second one becomes:

    StreamArrayReader::StreamArrayReader(char * filepath) {
        ifstream instream;
        instream.open(filepath);
        init_stream_array_reader(this, &instream);
        instream.close();
    }
    

    That is, instead of having one constructor calling another, both call a private friend!

提交回复
热议问题