0

I have created a class coor and overloaded a + operator

class coor
{
    coor(){std::cout<<"default constructor called\n";};
    coor operator +(coor param) const;
};

coor coor::operator+(coor param) const
{
    ....    
}


int main() {
    coor obj1;
    coor obj2;
    coor obj3 = obj1 + obj2;
    std::cin.get();
    return 0;
}

Why is the default constructor of obj3 is not called? It is called when declarartion and assignment and seperated.

Sack32
  • 53
  • 1
  • 3

2 Answers2

2

With

coor obj3 = obj1 + obj2

you copy-construct obj3 from the result of obj1 + obj2 (which is a so-called r-value and a temporary object).

Even though = is used here, it's not assignment but initialization.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    Your answer implies that a copy-constructor will be called. But this not true with C++17 (`operator+` returns a prvalue, so no copy constructor is involved here). – geza Dec 01 '18 at 12:58
1

"Why is the default constructor of obj3 is not called?" - Because of the rules of copy initialization - which is what is happening here.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70