- #1
yungman
- 5,644
- 227
I am still trying to study more on the Constructors. This is the program that can copy c-string into an Object member data.
I redo the program. I separate both Constructor into Separate Classes to eliminate all the confusions:
Constructors in line 8 and line 17 do the same thing, but the one in line 17 use new char[] where as in line 8 uses just a c-string and copy it in. The book tends to use the one in line 17. Not only I have to have extra step to create new memory, I have to have Destructor to delete the new memory. What is the advantage of line 17?
Thanks
I redo the program. I separate both Constructor into Separate Classes to eliminate all the confusions:
C++:
#include <iostream>
#include <cstring>
using namespace std;
const int Nsize = 51;
class vecC {
public:
char name[Nsize];
vecC(const char* desc)
{ strncpy_s(name, Nsize, desc, Nsize);
cout << "[Con1] for Cname: " << (*this).name << "\n\n";
}
void print() { cout << name << "\n\n"; }
};
class vecP {
public:
char*name;
vecP(const char* n)//Need to add const to use "Ptname" in main()
{ name = new char[Nsize];
strncpy_s(name, Nsize, n, Nsize);
cout << "[Con2] for name: " << (*this).name << "\n\n";
}
void print() { cout << (*this).name << "\n\n"; }
};
int main()
{
vecC CstrName("Cname");
vecP PtrName("Ptname");
vecC CopyCstr = CstrName;
vecP CopyPtr = PtrName;
CopyCstr.print();
CopyPtr.print();
return 0;
}
Constructors in line 8 and line 17 do the same thing, but the one in line 17 use new char[] where as in line 8 uses just a c-string and copy it in. The book tends to use the one in line 17. Not only I have to have extra step to create new memory, I have to have Destructor to delete the new memory. What is the advantage of line 17?
Thanks
Last edited: