C ++ Cannot invoke constructor directly in small example

I was wondering why I cannot call the constructor. Even this small example does not 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.

+6
source share
4 answers
 Sampleclass::Sampleclass() *qs = new Sampleclass::Sampleclass(); 

wrong. Sampleclass is a type , and Sampleclass::Sampleclass is a constructor . Because the correct syntax

 type identifier = new type(); 

you need to specify the type .

Therefore use

 Sampleclass *qs = new Sampleclass(); 

instead.


Notes:

  • If you didn’t know: with C ++ 11 you can just do

     Sampleclass() = default; 

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

+7
source

Yes, you cannot call ctor directly.

From the standard, class.ctor / 2

Because constructors have no names, they are never detected when looking up names;

You might want

 Sampleclass *qs = new Sampleclass; 

Then ctor will be called.

+4
source
 #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 refer to the constructor as a type when instantiating your class.

+1
source

In C ++, the constructor is called automatically if you define a new variable / instance of this class.

Follow the link below to see some simple examples of how to use the constructor: http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

0
source

Source: https://habr.com/ru/post/1237391/


All Articles