How to pass object to a function by reference in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Test {
	int n;
public:
	Test();
	void Set(int _n);
	void Print();
	~Test();
};

Test::Test() {
	cout << "Test()" << endl;
	n = 100;
}
void Test::Set(int _n) {
	n = _n;
}

void Test::Print() {
	cout << n << endl;
}

Test::~Test() {
	cout << "~Test()" << endl;
}

void Function(Test *o);

int main()
{
	Test o;

	o.Print();

	Function(&o);

	o.Print();

	return 0;
}

void Function(Test *o) {
	cout << "Function(Test *o)" << endl;
	
	o->Set(999);
}

/*
run:

Test()
100
Function(Test *o)
999
~Test()

*/

 



answered May 28, 2018 by avibootz

Related questions

1 answer 116 views
1 answer 175 views
1 answer 87 views
87 views asked Dec 19, 2024 by avibootz
2 answers 154 views
154 views asked Aug 22, 2022 by avibootz
...