0

So I call an overloaded addition of two Word objects with

Word w;
w + w;

the declaration and definition are:

Sentence operator+(const Word&) const;

Sentence Word::operator+(const Word& rightWord) const {
  std::cout <<"Entering function Word::operator+(const Word&)."<< std::endl;
  std::cout <<"Leaving function Word::operator+(const Word&).\n"<< std::endl;
}

After w + w is executed, a Sentence object is destructed (I overloaded the destructor to print to stdout) I created a sentence object earlier, but I don't think that is affecting it. I don't understand how a sentence object is being destructed when it wasn't even constructed (I overloaded the default constructor too).

I also don't understand why it would be created since I'm not even actually returning it. I ran it through gdb and it is definitely calling sentence's destructor when it exits the addition function.

Aiden Cullo
  • 312
  • 3
  • 15
  • Your function is declared to return a `Sentence` hence this `Sentence` has to be constructed and destructed at some point – tkausl Oct 08 '16 at 09:07
  • I overloaded the default constructor and it wasn't called, only the destructor. And when stepped through it in gdb I never hit a constructor @tkausl – Aiden Cullo Oct 08 '16 at 09:09
  • 2
    It's just UB, nothing is impossible. See [What happens when a function that returns an object ends without a return statement](http://stackoverflow.com/questions/39118324/what-happens-when-a-function-that-returns-an-object-ends-without-a-return-statem/39118529#39118529) – songyuanyao Oct 08 '16 at 09:10
  • Sentence Word::operator+(const Word& rightWord) const ------ That function creates a new word on w+w; and then destructs it cause it wasn't used. – Noam Rodrik Oct 08 '16 at 09:21
  • @tkausl: That's not correct. Yes, the function declaration requires the implementation to construct and destruct a `Sentence`, but it does not cause the implementation to do this automatically. The implementation does not meet the requirement, so it's just undefined behaviour. – Christian Hackl Oct 08 '16 at 10:27

1 Answers1

1

It's undefined behaviour if nothing is returned from a non-void function. All of the effects you have observed are not defined by the C++ language, are specific to your compiler and/or just random.

In fact, your compiler should issue a warning message for this piece of code, or even an error. For example, the following produces error C4716: 'Word::operator+': must return a value with Visual C++ 2015:

#include <iostream>

struct Sentence {};

struct Word {
Sentence operator+(const Word&) const;
};

Sentence Word::operator+(const Word& rightWord) const{
std::cout<<"Entering function Word::operator+(const Word&)."<<std::endl;
std::cout<<"Leaving function Word::operator+(const Word&).\n"<<std::endl;
} // error C4716

int main() {
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62