객체(Object)는 클래스의 인스턴스입니다. 중요한 점은 메모리가 클래스가 정의되는 시점이 아니라 객체가 실제로 생성되는 시점에 할당된다는 것입니다.
C++에서는 함수가 return 키워드를 사용하여 객체를 반환할 수 있습니다. 아래 예제 프로그램을 통해 이를 확인해 보겠습니다.
예제 코드
#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;
}실행 결과
위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.
Point 1 x = 5 y = 3 Point 2 x = 12 y = 6 The sum of the two points is: x = 17 y = 9
코드 상세 설명
1. Point 클래스 구조
Point 클래스는 두 개의 데이터 멤버인 x와 y를 가지고 있으며, 매개변수가 있는 생성자와 두 개의 멤버 함수로 구성됩니다.
- addPoint(): 두 개의 Point 값을 더한 결과를 저장한 임시 객체
temp를 생성한 뒤, 이를 반환합니다. - display(): 멤버 변수
x와y의 값을 화면에 출력합니다.
해당 코드는 다음과 같습니다.
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";
}
};2. main() 함수의 동작 흐름
main() 함수에서는 Point 클래스의 객체 세 개(p1, p2, p3)를 생성합니다. 먼저 p1과 p2의 값을 출력하고, 이어서 addPoint() 함수를 호출해 두 점의 합을 구하여 p3에 저장한 후 그 값을 출력합니다.
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();
추가로 알아두면 좋은 점
위 예제처럼 지역 객체를 반환할 때, 일반적으로 복사 비용이 발생할 수 있지만 최신 C++ 컴파일러는 RVO(Return Value Optimization, 반환 값 최적화)와 복사 생략(Copy Elision) 기술을 통해 불필요한 복사를 자동으로 제거합니다. 따라서 값으로 객체를 반환해도 대부분의 경우 성능 걱정 없이 안전하게 사용할 수 있습니다.