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,938 questions

51,875 answers

573 users

How to deep copy dynamic string with copy constructor in C++

1 Answer

0 votes
#include <iostream>

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

class String {
private:
	char *s;
	int size;
public:
	String(const char *_s = NULL); 
	~String() { delete[] s; }
	String(const String&); // copy constructor
	void print() { cout << s << endl; } 
};

String::String(const char *_s)
{
	size = strlen(_s);
	s = new char[size + 1];
	strcpy(s, _s);
}

String::String(const String &copy_s)
{
	size = copy_s.size;
	s = new char[size + 1];
	strcpy(s, copy_s.s);
}

int main()
{
	String s1("c++");
	String s2 = s1; // copy constructor run

	s1.print(); 
	s2.print();

	return 0;
}

/*
run:

c++
c++

*/

 



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

Related questions

1 answer 202 views
1 answer 125 views
2 answers 196 views
1 answer 140 views
1 answer 148 views
148 views asked Mar 23, 2018 by avibootz
...