Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,859 questions

51,780 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, 2018 by avibootz
...