Reputation:
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.
Upvotes: 9
Views: 29235
Reputation: 1
All answers containing new
are bad style in modern c++. In a similar small example, the following worked for me (in C17):
Sampleclass sc = Sampleclass();
Upvotes: 0
Reputation: 1
Remove resolution operator, I have an issue that Person::Person()
in child class and an error [Error] cannot call constructor 'Student::Person' directly [-fpermissive]
but after remove resolution operator solve this error
Upvotes: -1
Reputation: 172924
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.
Upvotes: 6
Reputation: 15229
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.
Upvotes: 9
Reputation: 752
#include <iostream>
using namespace std;
class Sampleclass
{
public:
Sampleclass();
};
Sampleclass::Sampleclass(){
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
Sampleclass *qs = new Sampleclass::Sampleclass();
return 0;
}
You tried to reference the constructor as a type when instantiating your class.
Upvotes: 1