How to use copy constructor to allow an objects to be passed to non class function in C++

1 Answer

0 votes
#include <iostream>

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

class Test {
	char *p;
public:
	Test(char *s);
	Test(const Test &obj);   // copy constructor
	~Test() {
		delete[] p;
	}
	char *get() { return p; }
};


Test::Test(char *s)
{
	p = new char[strlen(s) + 1];
	if (!p) {
		cout << "Error: Allocation" << endl;
		exit(1);
	}

	strcpy(p, s);
}


Test::Test(const Test &obj)
{
	p = new char[strlen(obj.p) + 1];
	if (!p) {
		cout << "Error: Allocation" << endl;
		exit(1);
	}

	strcpy(p, obj.p);
}

void print(Test obj)
{
	char *s;

	s = obj.get();
	cout << s << endl;
}

int main()
{
	Test o("c++");

	print(o); // copy constructor run

	return 0;
}

/*
run:

c++

*/

 



answered Mar 23, 2018 by avibootz
edited Mar 23, 2018 by avibootz

Related questions

1 answer 151 views
1 answer 156 views
156 views asked Mar 23, 2018 by avibootz
2 answers 161 views
...