C++ Cannot call constructor directly in small example

C++ Cannot call constructor directly in small example

b’

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

n

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

n

type identifier = new type();n

n

you need to specify the type here.

n

Therefore, use

n

Sampleclass *qs = new Sampleclass();n

n

instead.

n


n

Notes:

n

    n

  • If you didnt know: since C++11 you can simply do

    n

    Sampleclass() = default;n

    n

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

  • n

Yes, you cant call ctor directly.

n

From the standard, class.ctor/2

n

n

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

n

n

You might want

n

Sampleclass *qs = new Sampleclass;n

n

Then the ctor will be called.

C++ Cannot call constructor directly in small example

b’

#include <iostream>nusing namespace std;nnclass Sampleclassn{npublic:n    Sampleclass();n};nnSampleclass::Sampleclass(){nn}nnint main() {n    cout << !!!Hello World!!! << endl; // prints !!!Hello World!!!n    Sampleclass *qs = new Sampleclass::Sampleclass();n    return 0;n}n

n

You tried to reference the constructor as a type when instantiating your class.

Leave a Reply

Your email address will not be published.