How to “return an object” in C++?

C++ProgrammingServer Side Programming

An object is an instance of a class. Memory is only allocated when an object is created and not when a class is defined.

An object can be returned by a function using the return keyword. A program that demonstrates this is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};
int main() {
   Point p1(5,3);
   Point p2(12,6);
   Point p3;
   cout<<"Point 1\n";
   p1.display();
   cout<<"Point 2\n";
   p2.display();
   p3 = p1.addPoint(p2);
   cout<<"The sum of the two points is:\n";
   p3.display();
   return 0;
}

Output

The output of the above program is as follows.

Point 1
x = 5
y = 3
Point 2
x = 12
y = 6
The sum of the two points is:
x = 17
y = 9

Now, let us understand the above program.

The class Point has two data members i.e. x and y. It has a parameterized constructor and also 2 member functions. The function addPoint() adds two Point values and returns an object temp that stores the sum. The function display() prints the values of x and y. The code snippet for this is given as follows.

class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};

In the function main(), 3 objects of class Point are created. First values of p1 and p2 are displayed. Then the sum of values in p1 and p2 is found and stored in p3 by calling function addPoint(). Value of p3 is displayed. The code snippet for this is given as follows.

Point p1(5,3);
Point p2(12,6);
Point p3;
cout<<"Point 1\n";
p1.display();
cout<<"Point 2\n";
p2.display();
p3 = p1.addPoint(p2);
cout<<"The sum of the two points is:\n";
p3.display();
raja
Published on 21-Nov-2018 12:01:42
Advertisements