-2

I am a new c++ beginner.I have added private access identifier.Why does it throw this error?Thanks

class test
{
    private:
    test()
    {
    };
    ~test()
    {

    };
    public: void call()
    {
        cout<<"test"<<endl;
    } ;
};

error:

error: 'test::test()' is private|
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    It appears you could use a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to help you learn about C++. – Eljay Mar 21 '19 at 13:38

1 Answers1

2

If a constructor is private, you can't construct (define) an object of the class from outside the class itself (or outside a friend function).

That is, this is not possible:

int main()
{
    test my_test_object;  // This will attempt to construct the object,
                          // but since the constructor is private it's not possible
}

This is useful if you want to limit the construction (creation) of object to a factor function.

For example

class test
{
    // Defaults to private

    test() {}

public:
    static test create()
    {
        return test();
    }
};

Then you can use it like

test my_test_object = test::create();

If the destructor is private as well, then the object can't be destructed (which happens when a variables (objects) lifetime ends, for example when the variable goes out of scope at the end of a function).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    *"you can't construct (define) an object of the class*" ...except in a member or friend function. – eerorika Mar 21 '19 at 13:22