Is any constructor necessary in C++?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PUTUL

    Is any constructor necessary in C++?

    Is constructor necessary in C++?
  • rstiltskin
    New Member
    • Feb 2010
    • 14

    #2
    Not necessarily. It depends on your application.

    If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.

    If you want the member variables to be initialized, or if you want anything else done when the new object is created, then you have to write a constructor (or several constructors, depending on your requirements).

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.
      Actually, the compiler's default constructor calls the default constructors on each of the class data members.

      Creating the object is independent from calling constructors.

      If someone else designs a class with an object of your class as a member and then creates a object of their class using the compiler's default constructor, then your class must have a default constructor or their code won't compile.

      Comment

      • rstiltskin
        New Member
        • Feb 2010
        • 14

        #4
        ... then your class must have a default constructor ...
        ... meaning either you don't write any constructor (e.g. you use the compiler-supplied default constructor) OR you write your own default constructor.

        In that sense, "default constructor" simply means a constructor that takes no arguments. It may initialize data members or perform other functions.

        Comment

        Working...