can constructor be private or not

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sanjay123456
    New Member
    • Sep 2006
    • 125

    can constructor be private or not

    Dear friends,
    can constructor be private or not if yes How it possible ?

    sanjay
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    I don't think a constructor can be private - or if it can, I don't think it should. Whenever you create an instance of a class, you have to call SOME constructor. Since whatever class you are using to define this object is not of the same type, it shouldn't be able to access the private constructor.

    Comment

    • thefarmer
      New Member
      • Nov 2006
      • 55

      #3
      Originally posted by sanjay123456
      Dear friends,
      can constructor be private or not if yes How it possible ?

      sanjay

      hi there,

      Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created.
      You can also see how neither the prototype nor the later constructor declaration includes a return value; not even void.

      Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters. Remember that for overloaded functions the compiler will call the one whose parameters match the arguments used in the function call. In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed on the object declaration:

      If you do not declare any constructors in a class definition, the compiler assumes the class to have a default constructor with no arguments.

      so it is better to put then in public not on private..

      regards,

      Comment

      • DeMan
        Top Contributor
        • Nov 2006
        • 1799

        #4
        More to the point, a constructor is used to create an instance of a class. For a class (other than a static class, which doesn't (always) need to be initialised) it doesn't make sense for a constructor to be private.

        That is constructors are the crux of Object Oriented Programming, and the point of OOP is that you create objects which can do things, rather than just trying to do things on objects....to create an object, you need to be able to see the method to create it (the constructor).

        It is probably possible to create objects without using the constructor (in some situations), but I don't think it makes (too much) sense for a constructor to be limited only to the class which it creates an instance of.

        Certainly even if such cases exist they would be unlikely to come up in everyday situations.

        Comment

        Working...