C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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

Learn: How to overload pre-increment 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

What are nameless temporary objects in C++?

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-increment operator overloading.

C++ program for nameless temporary objects in C++ and its use in pre-increment operator overloading

Consider the program:

using namespace std;
#include <iostream>

class Sample {
  // private data section
  int count;

  // default constructor
  Sample() { count = 0; }

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

  // Operator overloading function definition
  Sample operator++() {
    // returning count of Sample
    // There is no new object here,
    // Sample(count): is a constructor by passing value of count
    // and returning the value (incremented 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;

    cout << "S2 :" << endl;
  return 0;


S1 :
Value of count : 101
S2 :
Value of count : 101
S1 :
Value of count : 102
S2 :
Value of count : 102
S1 :
Value of count : 103
S2 :
Value of count : 103
S1 :
Value of count : 104
S2 :
Value of count : 104
S1 :
Value of count : 105
S2 :
Value of count : 105

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 incremented value to calling function.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.