+ 1

Why use constructor under public?

So, what will happens if we don't put class myclass{ public: myclass() {}; }; and put it outside. And how "exiting class" works. I mean the its said that "destructor" runs when a class is exited. But I couldn't understand in those examples how it happens. How class exit works.

22nd Apr 2018, 1:52 PM
Akib
Akib - avatar
3 Réponses
+ 3
What do you mean put it outside? If you mean outside of public, then you wouldn't be able to create objects from that class using the default constructor, because it would be protected by the private or protected access modifiers. If you mean defining the function outside of the class, it is totally possible: class myclass { public: myclass(); }; myclass::myclass () {}; Exiting the class just means when an instantiation of the class (an object) reaches the end of its scope. If you create an object in main, the destructor for that object will be called at the end of main. Try defining the destructor like this and mess around with making objects in different functions: class MyClass { public: ~MyClass() { cout << "Object destroyed\n"; } };
22nd Apr 2018, 3:02 PM
Zeke Williams
Zeke Williams - avatar
+ 16
No, Constructors can be public, private, protected or default(no access modifier at all). Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too. One of the use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time.
22nd Apr 2018, 6:25 PM
Baraa AB
Baraa AB - avatar
+ 2
Baraa AB just to be clear, I know you can still access the constructor when it is private, but it would have to be through other methods.
22nd Apr 2018, 6:53 PM
Zeke Williams
Zeke Williams - avatar