Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using class alias for its constructor definition

This minimum reproducible piece of code

class MyClass
{
public: 
    explicit MyClass();

    ~MyClass();
};  

using MyClassAlias = MyClass;

MyClassAlias::MyClassAlias()
{

}

MyClassAlias::~MyClassAlias()
{

}

int main()
{
    MyClassAlias obj;

    return 0;
}   

gives the error:

a.cpp:11:1: error: ISO C++ forbids declaration of ‘MyClassAlias’ with no type [-fpermissive]
   11 | MyClassAlias::MyClassAlias()
      | ^~~~~~~~~~~~
a.cpp:11:1: error: no declaration matches ‘int MyClass::MyClassAlias()’
a.cpp:11:1: note: no functions named ‘int MyClass::MyClassAlias()’
a.cpp:1:7: note: ‘class MyClass’ defined here
    1 | class MyClass
      |       ^~~~~~~

Only if I replace MyClassAlias::MyClassAlias() with MyClassAlias::MyClass(), it gets cured. At the same time, as you can see, it is okay to have MyClassAlias::~MyClassAlias() (the compiler gives no error).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to fix this: to have consistency in naming?

>Solution :

The "names" (although these are not names in the technical sense of the standard) of the constructor and destructor are MyClass and ~MyClass respectively. They are based on the injected class name. You need to use these two to define them or write any declaration for them. You cannot use an alias name for these.

The same does not apply to the class name before the ::. It can be the name of an alias.

It seems that GCC accepts the alias as well for the destructor definition, but as far as I can tell that is not standard-conforming.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading