Constructors are overloaded - Constructor and Destructor

Q.  Can constructors be overloaded?
- Published on 17 Jul 15

a. Yes
b. No

ANSWER: Yes
 

    Discussion

  • Nihal   -Posted on 07 Oct 15
    Yes, Constructor can be overloaded in similar way as function overloading. According to the number and type of argument passed, specific constructor is called. Constructor is called automatically when object of the class is created, so you have to pass argument to the constructor while creating object.
    Example:
    class Area
    {
    private:
    int length;
    int breadth;

    public:
    Area(): length(5), breadth(2){ } // Constructor without argument
    Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument

    void AreaCalculation() { cout<<"Area =:: "<<(length*breadth); }

    };
    int main()
    {
    Area obj1,obj2(10,20);

    cout<<"Default Area when no argument is passed."< obj1.AreaCalculation();

    cout<<"\nArea when (2,1) is passed as argument.\n"< obj2.AreaCalculation();

    return 0;
    }

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)