Monday, August 22, 2022

C++ Constructor

 

1. C++ Default Constructor

A constructor in C++ is a special method that is automatically called when an object of a class is created.
 

Default constructors

include <iostream>


class dog
{
public:
  int x, y;

// Default Constructor declared
  dog()
  {
    x = 45;
    y = 10;
  }
};

int main()
{
  // Default constructor called automatically when the object is created
  dog a; 

 

2. Parameterized constructors

 
#include <iostream>

class dog
{
private:
  int a, b;
public:
  // Parameterized Constructor
  dog(int x, int y)
  {
    a = x;
    b = y;
  };

  int getX()
  {
    return a;
  };

  int getY()
  {
    return b;
  };
};
int main()
{
  dog v(10, 15); // Constructor called

  cout << "a = " << v.getX() << endl; // values assigned by constructor accessed
  cout<< "b = " << v.getY() << endl;

  getch();
}

 

3. Copy Constructor

A copy constructor is a special type of constructor which initializes all the data members of the newly created object by copying the contents of an existing object. The compiler provides a default copy constructor.

  #include <iostream>  
  
    class dog 
    {  
       public:  
        int x;  
        dog(int a)                // parameterized constructor.  
        {  
          x=a;  
        }  
        dog(dog &i)               // copy constructor  
        {  
            x = i.x;  
        }  
    };  
    int main()  
    {  
      dog a1(20);               // Calling the parameterized constructor.  
     dog a2(a1);                //  Calling the copy constructor.  
     cout<<a2.x;  
      getch()
    }  



4. Multiple constructors


#include <iostream>


class dog
{
  int a, b;
public:
  // Constructor with no argument
  dog()
  {
    a= 2;
    b= 3;
  };
  // constructor with one argument
  dog(int x)
  {
    a=b=x;
  };
  // Constructor with two arguments
  dog(int x, int y)
  {
    a= x;
    b= y;
  };
  int area(void)
  {
    return(a*b);
  };
  void display()
  {
    cout<<"area="<< area() <<endl;
  };
};
int main()
{
  // Constructor Overloading with two different constructors of class name
  dog s;
  dog s2(6);
  dog s3( 3, 2);

  s.display();
  s.display();
  s.display();
 getch()
}