Constructor Access Specifer level

hi,
What level of access specifer do C++ programmers put constructors? Public or private?

Like this code for example, the access specifer is public, is that good practice making it public?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
using namespace 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;
  
}
If you make the constructor private, you wouldn't be able to create an instance of the class like you have in your current code.

Generally I'd only make it private if I was making a singleton.
Last edited on
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.
thanks for the quick responses everyone! and computer geek i know the quick responses are the reason why i love this site!
Topic archived. No new replies allowed.