简体   繁体   中英

Calling a constructor of included class within class constructor

In class argList constructor is the instruction

args_[0] = fileName(argv[0]);

When searching for method fileName(...) it turns out that it should be a constructor of class fileName :

inline Foam::fileName::fileName(const char* str) //Construct as copy of character array.
: string(str)    //Construct as copy of character array.
{
    stripInvalid();    //Strip invalid characters from the given string.
}

Two Questions:

  1. Is it really the constructor of class fileName that is called?
  2. Hasn' t the constructor of fileName to be static if it was called like this?

greetings streight

  1. Yes - this is a really constructor of fileName class - there's no return value and the name of the method is the same as the name of the class.

  2. This is not a call to the constructor, but the definition of the constructor (I guess :: is what is confusing you):

     inline Foam::fileName::fileName(const char* str) //Construct as copy of character array. 

    This is the call to the constructor:

     args_[0] = fileName(argv[0]); 

    There's no static constructor in C++.

'1. Is it really the constructor of class fileName that is called?

Yes. The constructor is called because it args_[0] is assigned a new instance of the fileName class.

'2. Hasn' t the constructor of fileName to be static if it was called like this?

No. A constructor cannot be static. This is one of the correct ways to construct objects.

Is it really the constructor of class fileName that is called?

Indirectly, yes. For a class T , the expression T(args) creates a temporary object, and initialises it by calling a suitable constructor for the arguments.

In this case, this constructor matches the argument type, so that's what is used.

Hasn't the constructor of fileName to be static if it was called like this?

No, constructors can't be declared static. They can always be used to initialise either named variables, or temporaries like this one, with no special declarations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM