Friday, 22 June 2018

12-D Prog: 05 Write a program to show the working of all types of Constructors and Destructors.

Types of Constructors
   5A. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.
  1. // Cpp program to illustrate the
    // concept of Constructors
    #include <iostream.h>

    class construct
    {
    public:
        int a, b;
             
            // Default Constructor
        construct()
        {
            a = 10;
            b = 20;
        }
    };
    void main()
    {
            // Default constructor called automatically
            // when the object is created
        construct c;
        cout << "a: "<< c.a << endl << "b: "<< c.b;
        
    }

    Output:
    a: 10
    b: 20
    5B. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
    1. // CPP program to illustrate
      // parameterized constructors
      #include<iostream.h>

      class Point
      {
          private:
              int x, y;
          public:
              // Parameterized Constructor
              Point(int x1, int y1)
              {
                  x = x1;
                  y = y1;
              }
           
              int getX()      
              {
                  return x;
              }
              int getY()
              {
                  return y;
              }
          };
      void main()
      {
          // Constructor called
          Point p1(10, 15);
          // Access values assigned by constructor
          cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
          
      }
        output:
      p1.x = 10, p1.y = 15
      Paramaterized Constructor video: 5minutes
      https://www.youtube.com/watch?v=2LxU7vroRj0
    2. 
      

No comments:

Post a Comment