9

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.

  • What are you trying to do? Why are you using `new`? Also, you can't directly call a constructor in C++. – TartanLlama Dec 04 '15 at 09:43
  • 4
    It's just C++... constructors are not regular functions. See [this](http://stackoverflow.com/questions/33079486/difference-between-constructor-calls-with-and-without/33079632) question and answers – Paolo M Dec 04 '15 at 09:43
  • I need to have a object on the heap, not the stack. This is just one small example where I also have the problem. –  Dec 04 '15 at 09:46

4 Answers4

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

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
6

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1
#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.

Mike P
  • 742
  • 11
  • 26
-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

Shunya
  • 2,344
  • 4
  • 16
  • 28