This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

What is constructor and what are the properties of constructor? Write a program showing the example of Parameterized constructor.

 Constructor is a special member function that is invoked automatically whenever an object of a class is created. It is used to initialize the data members of the class. The constructor has the same name as the class and does not have any return type, not even void.

The properties of constructor are:

  1. It has the same name as the class.
  2. It is automatically called whenever an object of the class is created.
  3. It does not have any return type, not even void.
  4. It can be overloaded.
  5. It can have default arguments.

Here is an example program showing the use of Parameterized constructor:

#include <iostream>
using namespace std;
class Rectangle {
   private:
      float length;
      float breadth;
   public:
      Rectangle(float l, float b) {
         length = l;
         breadth = b;
      }
      float area() {
         return length * breadth;
      }
};
int main() {
   Rectangle r(4.5, 6.7);
   cout << "Area of rectangle: " << r.area() << endl;
   return 0;
}

In the above program, we have defined a class named Rectangle with private data members length and breadth. We have defined a parameterized constructor that takes two float arguments, l and b, and initializes the data members length and breadth with these values. We have also defined a public member function area() that calculates and returns the area of the rectangle.

In the main() function, we have created an object r of the Rectangle class with the values 4.5 and 6.7 passed as arguments to the constructor. We have then called the area() function on the object r to calculate and print the area of the rectangle.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget