#include <iostream>
#include <string>
usingnamespace std;
//a constructor is a function that gets called automatically the second you create an object.
//same as creating a function with a weird rule, never have a return type, is type the construcotr name it is always the same as the class name.
class johnclass{
public:
//constructor same name as the class.
johnclass(string z){
setName(z);
}
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string name;
};
int main()
{
//when ever you create an object from a class each object has its own variables and there values. they dont overwrite each
johnsclass bo("Lucky John");
cout << bo.getName(); //cant forget the () as it is a function!
johnsclass bo2("Sally Mcsalad");
cout << bo2.getName();
return 0;
}
You almost always want to have public constructors. If the constructor is private you will not be able to use that constructor to create an instance of the class outside the class member functions.
One use of private constructor is when making the copy constructor and copy assignment operator private to make it impossible to create copies of the objects.
If you want people to be able to write code that calls the constructor (i.e. people can write code that directly creates the object using that constructor), then make it public. If you don't, make it private.
Sometimes you'll want people to be able to do it, so you make it public. Sometimes you don't, so you make it private. "Good practice" is not a blanket "this kind of thing must be public, and this kind of thing must be private". "Good practice" is doing whatever is appropriate for how the coder should be using the object.
Check out those time stamps! This is why you have to love this site.
Another reason to make a constructor private is if you make an object that you want only to be a base class. I have no idea why you would want to do this, but generally when you're talking about private constructors you have to reach for answers anyway.