C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

What are nameless temporary objects in C++ and its use in pre-decrement operator overloading?

Learn: How to overload pre-decrement operator by using the concept of nameless temporary objects in C++, this articles contains solved example on this concept?

Prerequisite: operator overloading and its rules

Sometimes to reduce the code size, we create nameless temporary object of class.

When we want to return an object from member function of class without creating an object, for this: we just call the constructor of class and return it to calling function and there is an object to hold the reference returned by constructor.

This concept is known as nameless temporary objects, using this we are going to implement a C++ program for pre-decrement operator overloading.

Consider the program:

using namespace std;
#include <iostream>

class Sample
{
	//private data section
	private:
	int count;
	
	public:
	//default constructor
	Sample()
	{ count = 0;}      

	//parameterized constructor
	Sample(int c)
	{ count = c;}      

	//Operator overloading function definition
	Sample operator--()
	{ 
		--count;
		//returning count of Sample
		//There is no new object here, 
		//Sample(count): is a constructor by passing value of count
		//and returning the value (decremented value)
		return Sample(count);
	}
	
	//printing the value
	void printValue()
	{
		cout<<"Value of count : "<<count<<endl;
	}
};

//main program
int main()
{
	int i = 0;
	Sample S1(100), S2;

	for(i=0; i< 5; i++)
	{    
		S2 = --S1;

		cout<<"S1 :"<<endl;
		S1.printValue();

		cout<<"S2 :"<<endl;
		S2.printValue();
	}
	return 0;    
}

Output

S1 :
Value of count : 99
S2 :
Value of count : 99
S1 :
Value of count : 98
S2 :
Value of count : 98
S1 :
Value of count : 97
S2 :
Value of count : 97
S1 :
Value of count : 96
S2 :
Value of count : 96
S1 :
Value of count : 95
S2 :
Value of count : 95

In this program, we used nameless temporary object in overloaded member function.

Here, we did not create any object inside the member function. We are just calling the constructor and returning decremented value to calling function.









COMMENTS