In Object Oriented Programming (OOP) there is implementation of constructors but the question that I usually get from some people is “Why should one have to create a constructor explicitly yet programming languages allow the programmers not to create a constructor for a class at all?” In this good programming practice tutorial I am going to answer that question by giving you some of the use of constructors and at the end of it all you will get to know why creating constructors for classes is important.
It’s true that programming languages allow programmers not to create a constructor explicitly for a class but that doesn’t mean there is no constructor created at all. Once a programmer doesn’t create a constructor(s) for a class explicitly then a default constructor is automatically generated.
When instantiating a particular class the constructor is used. This is the main reason why even if the programmer does’t explicitly create a constructor for a class a default constructor is generated because it will be required to instantiate it. At the time of instantiating a class, the properties of the object to be created may be initialize using the constructor.
In summary the major two uses of constructors include the following
- Instantiating a class.
- Initializing properties/variables of an object.
The reason why one should create a constructor explicitly yet programming languages allow the programmers not to create a constructor for a class at all is that the default constructors that are generated in case there is no constructor created explicitly are simply empty and can not do any initialization if required. In cases where initialization of object properties is required then consider creating a constructor explicitly which can take in arguments that will be used to initialize the properties of the object.
- Previous Post: Short Form PHP Tags Vs Long Form PHP Tags