Why do we need to initialize the parameters beforehand in a parameterized constructor?

Viewed 69

I'm declaring one class comp for adding complex numbers the error pops up while declaring the third comp object in the add() function error: no matching function for call to 'comp::comp()'

code given below works absolutely fine

 class comp
    {
        float real;
        float img;
    
    public:
        comp()
        {
            real=img=0;
        }
    
        comp(float a,float b)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };
    

In the code blow now that I've commented the Default constructor this produces an error

    class comp
    {
        float real;
        float img;
    
    public:
        /*comp()
        {
            real=img=0;
        }*/
    
        comp(float a,float b)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };
    

In the code below now that I've initialized the parameters in the parameterized constructor this also works absolutely fine

    class comp
    {
        float real;
        float img;
    
    public:
    
        comp(float a=0,float b=0)
        {
            real=a;
            img=b;
        }
    
        void display()
        {
            cout<<real<<"+"<<img<<"i"<<endl;
        }
    
        friend comp add(comp, comp);
    };

I'm pasting the code for the add() function below

    comp add(comp c1, comp c2)
    {
        comp c3;   //*The error pops up at this declaration*
        c3.real=c1.real+c2.real;
        c3.img=c1.img+c2.img;
        return c3;
    }
1 Answers

You're not "initializing parameters", you're declaring a function with default values for the parameters. This makes it possible to call the function without explicitly passing anything, so it is callable with no parameters.

Related