Home > Software design >  How to understand const Someclass& a in constructor
How to understand const Someclass& a in constructor

Time:07-18

I'm trying to understand the code below. More specifically, why is b.x in the main function 5?
As far as I understand, I have a constructor Someclass(int xx):x(xx){} in the class which sets my attribute x to xx. Therefore, a.x in the main function is 4.
But what do the lines
Someclass(const Someclass& a){x=a.x;x ;} and
void operator=(const Someclass& a){x=a.x;x--;} do?
Is the first one also a constructor? And I think the second one overrides the '=' operation. But with what? And what is this a in the class?

Since I am still quite new to programming, I would really appreciate your help!

 class Someclass{
    public:
    int x;
    public:
    Someclass(int xx):x(xx){}
    Someclass(const Someclass& a){x=a.x;x  ;}
    void operator=(const Someclass& a){x=a.x;x--;}

};

int main()
{
 
    Someclass a(4);
    Someclass b=a;
    cout<<"a:"<<a.x<<endl; //prints 4
    cout<<"b:"<<b.x<<endl; //prints 5
   
    return 0;
}

CodePudding user response:

When you instantiate a with the following line:

Someclass a(4);

You are calling the "normal" constructor, namely:

class Someclass {
  public:
    int x;
  public:
    Someclass(int xx):x(xx){} // <= This one
    Someclass(const Someclass& a){x=a.x;x  ;}
    void operator=(const Someclass& a){x=a.x;x--;}
};

When you instantiate b with the following line:

Someclass b=a;

You are creating a new object (b) from an already existing one (a). This is what the copy constructor is for.

class Someclass {
  public:
    int x;
  public:
    Someclass(int xx):x(xx){}
    Someclass(const Someclass& a){x=a.x;x  ;} // <= This one
    void operator=(const Someclass& a){x=a.x;x--;}
};

To put it simply, the equals operator is for the already instantiated object. This operator would be called if you wrote the following:

Someclass a(4);
Someclass b = a;
b = a;
std::cout << b.x << std::endl; // Prints 3
  • Related