C++ Cannot call constructor directly in small example

I was wondering, why I cannot call a constructor. Even this small example fails to compile with the message:

Klassentest.cpp:24:27: error: cannot call constructor 'Sampleclass::Sampleclass' directly [-fpermissive]

Code:

#include <iostream>
using namespace std;

class Sampleclass
{
   public:
    Sampleclass();
};

Sampleclass::Sampleclass(){

}

int main() {
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
    Sampleclass::Sampleclass() *qs = new Sampleclass::Sampleclass();
    return 0;
}

I used the Cygwin g++ compiler in version 4.9.3-1.

Thank you for your help.


Solution 1:

Sampleclass::Sampleclass() *qs = new Sampleclass::Sampleclass();

is wrong. Sampleclass is a type while Sampleclass::Sampleclass is a constructor. Since the correct syntax is

type identifier = new type();

you need to specify the type here.

Therefore, use

Sampleclass *qs = new Sampleclass();

instead.


Notes:

  • If you didn't know: since C++11 you can simply do

    Sampleclass() = default;
    

    in the class definition and the default constructor will be defined.

Solution 2:

Yes, you can't call ctor directly.

From the standard, class.ctor/2

Because constructors do not have names, they are never found during name lookup;

You might want

Sampleclass *qs = new Sampleclass;

Then the ctor will be called.