Click here to Skip to main content
15,920,596 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
C++
#include <iostream>

using namespace std;
class A 
{
  int x;
  public:
  A(){
      cout<<"default constructor called\n";
  }
  A(int a)
  {
      x=a;
  }
  A(const A&p)
  {
      cout<<"Copy constructor called\n";
      x=p.x;
  }
  
  A operator+(A &p)
  {  
      cout<<"+ called\n";
      A temp;
      temp.x=x+p.x;
      return temp;
  }
};
int main()
{
    // cout<<"Hello World";
A a1(3),a2(4);
A a3=a1+a2;
    return 0;
}


What I have tried:

I tried googling but nothing found. See in above code I have written the statement inside each constructor to determine which is called.

In the line-
A a3=a1+a2;
here a1 will call + operator and a2 will be passed as an argument to the + operator function so "+ called" gets printed on console . Now inside + operator temp object created so for that default constructor gets called and "default constructor called" gets printed on console. So when + operator returns temp so then copy constructor must be called for a3 because now the line becomes - A a3 = temp;
but the values are copied inside a3 because I have printed on console but how no assignment operator , copy constructor called . If copy constructor gets called then it must be printed "Copy constructor called" on console.
Posted
Updated 14-Oct-22 23:01pm
v2

1 solution

Quote:
A operator+(A &p)
{
cout<<"+ called\n";
A temp;
temp.x=x+p.x;
return temp;
}
The default constructor is called in order to create the temp object, you may see it replacing the above code with
C++
A operator+(A &p)
 {
     A temp;
     cout<<"+ called\n";
     temp.x=x+p.x;
     return temp;
 }
Then the compiler performs a copy elision optimization (see for instance Copy elision - cppreference.com[^] ).
 
Share this answer
 
Comments
Richard MacCutchan 15-Oct-22 5:18am    
+5.
I looked at that link earlier, but even as a native English speaker I struggled to understand it fully.
CPallini 15-Oct-22 7:01am    
:-)
Thank you, Richard.
merano99 15-Oct-22 19:37pm    
+5
CPallini 16-Oct-22 3:40am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900