Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Trees

Liquid Web Managed Dedicated Server: RAID 1 SSD with 16GB of RAM minimum! 24/7 On-Site Heroic Support! Industry-Leading SLA!

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Liquid Web Cloud VPS Hosting

8,956 questions

12,358 answers

573 users

How to use constructor and destructor for dynamic string allocation in C++

1 Answer

0 votes
#include <iostream>

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

class Test {
	char *p;
	int len;
public:
	Test(char *_p);
	~Test();
	void print();
};

Test::Test(char *_p)
{
	len = strlen(_p);
	p = new char[len + 1];
	if (!p) {
		cout << "new char error" << endl;
		exit(1);
	}
	strcpy(p, _p);
	cout << "new char[len + 1]: " << _p << endl;
}

Test::~Test()
{
	cout << "delete[] p: " << p << endl;
	delete[] p;
}

void Test::print()
{
	cout << "print: " << p << endl;
}

int main()
{
	Test o1("c++"), o2("java"), o3("php");

	o1.print();
	o2.print();
	o3.print();

	return 0;
}

/*
run:

new char[len + 1]: c++
new char[len + 1]: java
new char[len + 1]: php
print: c++
print: java
print: php
delete[] p: php
delete[] p: java
delete[] p: c++

*/

 




answered Mar 20 by avibootz
...