use FORTRAN and not C++. In FORTRAN everything is so elegant and beautiful, no pointer no memory leaks magnificent, and it runs much faster :) :) :) |
C++ is elegant too, if you do it right. You are just doing things in an overly complicated manner. I'm sure you could also do things in FORTRAN which make the code more complicated than it needs to be.
Also, high level languages don't get much faster than C and C++.
Just out of pure curiosity is it possible to get along only with the copy constructor or I must always have the overloaded (=) ? |
The so called "rule of 3" says that there are 3 key areas of a class:
1) Copy constructor
2) Assignment operator
3) Destructor
If you find yourself having to write one of these functions, you likely have to write all 3.
The updated version of the code is included below |
You are still leaking memory.
your default constructor new's a buffer.
The assignment operator new's another buffer without deleting the old one.
Since the buffer size is not changing, you don't need to reallocate with new in the assignment operator.
...
but again... you don't need (and shouldn't be using) new at all. It's just making your code way more complicated than it needs to be.
The simpler way to do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class test
{
public:
int x,y;
string point; // <- make it a string
test() {
point = "Test1"; // then you can just assign it normally
x = 0;
y=0;
}
test(int a,int b) {
point = "Test2"; // ditto
x=a;
y=b;
}
// no need to write copy ctor or destructor anymore
// strings are automatically deep copied, so no worry about memory leaks
// or pointer management or any of that.
test operator+(test t1) {
test temp;
temp.x=x+t1.x;
temp.y=y+t1.y;
temp.point = t1.point; // normal assignment instead of strncpy
return temp;
}
// no need for assignment operator, either. For same reasons as above
void show(){cout<<point<<endl;}
};
|
EDIT:
Or if you don't want to use strings for some weird reason... another simpler alternative:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class test
{
public:
int x,y;
char point[10]; // <- make it an array (no need for dynamic size)
test() {
strcpy(point,"Test1"); // can strcpy it
x = 0;
y=0;
}
test(int a,int b) {
strcpy(point,"Test2"); // can strcpy it
x=a;
y=b;
}
// no need to write copy ctor or destructor anymore
// arrays are automatically deep copied, so like strings, there's no worry
test operator+(test t1) {
test temp;
temp.x=x+t1.x;
temp.y=y+t1.y;
strcpy(temp.point,t1.point); // <-
return temp;
}
// no need for assignment operator, either. For same reasons as above
void show(){cout<<point<<endl;}
};
|