Seong
Seong

Reputation: 616

Is it possible to have constructor have different name as the class declared?

I have a quick question while reading a source code. AFAIK, the name of a constructor should be identical to the class declared. But, the following code has a different name as a constructor. Anybody can tell me why this code works?

class directFieldMapper
:
    public FieldMapper
{
    const labelUList& directAddressing_;

    bool hasUnmapped_;

public:

    // Constructors

        //- Construct given addressing
        patchFieldSubset(const labelUList& directAddressing)
        :
            directAddressing_(directAddressing),
            hasUnmapped_(false)
        {
            if (directAddressing_.size() && min(directAddressing_) < 0)
            {
                hasUnmapped_ = true;
            }
        }

    //- Destructor
    virtual ~directFieldMapper()
    {}
}

Ok, I found that this class is not in the source code list in the Makefile. So, this class is never compiled.

Upvotes: 0

Views: 286

Answers (1)

eerorika
eerorika

Reputation: 238311

Is it possible to have constructor have different name as the class declared?

No.

AFAIK, the name of a constructor should be identical to the class declared.

Correct.

But, the following code has a different name as a constructor.

The code is ill-formed according to C++ standard.

Anybody can tell me why this code works?

If it works, then it is due to some language extension. You can consult the manual of your compiler about language extensions it provides, and how to enable / disable them.

Being ill-formed, all compilers are required to issue a diagnostic message, or else they are not compliant. Example output from the GNU compiler:

error: ISO C++ forbids declaration of 'patchFieldSubset' with no type [-fpermissive]

         patchFieldSubset(const labelUList& directAddressing)

                                                            ^

warning: non-static reference 'const labelUList& directFieldMapper::directAddressing_' in class without a constructor [-Wuninitialized]

     const labelUList& directAddressing_;

                       ^~~~~~~~~~~~~~~~~

error: expected ';' after class definition

 }
  ^

Upvotes: 5

Related Questions