C++ Passing and Returning Object from Function

Passing objects to a function in C++ is similar to passing a structure or union variable. In C++, Objects are passed using call by value. The called function must declare an object as a formal parameter.

C++ Program to Pass Object to Function

#include <iostream>
using namespace std;

class Point { 
   private:
     int x_cor, y_cor;
      
   public:
     Point(int x, int y) {
     	x_cor = x;
     	y_cor = y;
	 }
	
	int getX(){
		return x_cor;
	}
	
	int getY(){
		return y_cor;
	}
};

void drawLine(Point p1, Point p2) {
    cout << "Drawing line from point (" << p1.getX() << "," << 
	p1.getY() << ") To (" <<  p2.getX() << "," << p2.getY() << ")";
}

int main() {
    Point p1(2,3), p2(6,7);
    
    // Passing p1 and P2 to function drawLine
    drawLine(p1, p2);
    
    return 0;
}
Output
Drawing line from point (2,3) To (6,7)

In above program, we are creating two objects p1 and p2 of Point class by passing some initial values to constructors. Then we passed p1 and p2 to function drawLine, like passing variables of any other basic data types. Now, inside drawLine function we can access all public member variables and member functions.


Returning Objects from a Function in C++

Returning an object from a function is similar to returning a structure or union variable. Function returning object must declare it's return type as object.

C++ Program to Return Object from a Function

#include <iostream>
using namespace std;

class Point { 
   private:
     int x_cor, y_cor;
      
   public:
   	Point(){
	}
   	
    Point(int x, int y) {
     	x_cor = x;
     	y_cor = y;
	}
	
	void setPoint(int x, int y) {
		x_cor = x;
     	y_cor = y;
	}
	
	int getX(){
		return x_cor;
	}
	
	int getY(){
		return y_cor;
	}
};

Point getMidPoint(Point p1, Point p2) {
    Point mid;
    mid.setPoint((p1.getX() + p2.getX())/2, (p1.getY() + p2.getY())/2);
    
    return mid;
}

int main() {
    Point p1(2,3), p2(6,7), p3;
    
    
    p3 = getMidPoint(p1, p2);
    
    cout << "Mid Point(" << p3.getX() << "," << p3.getY() << ")";
    
    return 0;
}
Output
Mid Point(4,5)