2

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).

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

JenyaKh
  • 2,040
  • 17
  • 25

1 Answers1

2

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.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • I am sorry, what do you mean, constructors do not have names? – JenyaKh Jul 13 '22 at 15:30
  • 1
    @JenyaKh See [Constructors do not have names](https://timsong-cpp.github.io/cppwp/n4868/class.ctor.general#1.2) and [this question](https://stackoverflow.com/questions/71724811/does-a-constructor-has-a-type-in-c-since-it-is-a-special-member-function) that i asked some time ago. – Jason Jul 13 '22 at 15:32