-1

I was trying to define a copy constructor in my example here. However, I found that the default/implicit constructor doesn't make compiler happy if the copy constructor has to be used. Why is it so? Is there any reason behind it?

class DemoCpyConstructor
{

private:

    int priv_var1;
    int priv_var2;

public:

    void setDemoCpyConstructor(int b1, int b2)
    {
        std::cout<<"The Demo Cpy Constructor Invoked"<<std::endl;
        priv_var1 = b1;
        priv_var2 = b2;

    }

    void showDemoCpyConstructor()
    {
        std::cout<<"The priv_var1 = "<<priv_var1<<std::endl;
        std::cout<<"The priv_var2 = "<<priv_var2<<std::endl;
    }

    DemoCpyConstructor(const DemoCpyConstructor &oldObj)
    {
        std::cout<<"Copy Constructor Invoked.."<<std::endl;
        priv_var1 = oldObj.priv_var1;
        std::cout<<"Tweaking the copy constructor"<<std::endl;
        priv_var2 = 400;
    }


};


int main(int argc, char *argv[])
{
    DemoCpyConstructor oldObj;
    oldObj.setDemoCpyConstructor(120,200);
    oldObj.showDemoCpyConstructor();

    DemoCpyConstructor newObj = oldObj;

    newObj.showDemoCpyConstructor();

    return 0;
}

This is what the error, I get -

error: no matching function for call to ‘DemoCpyConstructor::DemoCpyConstructor()’
user3629119
  • 151
  • 1
  • 9

1 Answers1

1

Whenever you define any kind of constructor (means conversion, copy) and you want to use the default one as well you have to explicitly provide it. its the rule

Ali Kazmi
  • 1,460
  • 9
  • 22