I'm sure that any good book on C++ programming would explain the details.
I have been using Beginning Visual C++ 2008 by Ivor Horton because it is written for the compiler I'm using. I'm ready for another book that goes deeper though now.
I've seen the C++ Primer recommended by others on this site and it looks to be QUITE comprehensive. Here's a link for that book:
http://www.amazon.com/Primer-4th-Stanley-B-Lippman/dp/0201721481/ref=pd_sim_b_7
As regards your current problem I'll just give some code for you to consider.
The following program includes the needed assignment operator and copy constructor (so you can pass a Point2 object by value OR construct one Point2 object from another one).
I also included a constructor which does double duty as a no-argument constructor (replacing your 1st one) and will also accept two float values (replacing your 2nd constructor). I used an initializer list format so you would see something new for writing constructors.
I put cout statements in the functions so you could easily see what is being called when throughout the program execution.
This program:
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
using namespace std;
class Point2
{
private:
float *x, *y;
public:
//Constructors
Point2(float left=0.0f, float top=0.0f): x(new float(left)), y(new float(top))
{ cout << "combo ctor called\n"; }
// copy constructor
Point2(const Point2& pt): x(new float(*pt.x)), y(new float(*pt.y))
{ cout << "COPY ctor called\n"; }
//Destructor
~Point2()
{
cout <<"destructor called\n";
delete x;
delete y;
}
// operator
Point2& operator=(const Point2& pt)
{
cout << "assignment operator called\n";
*x = *pt.x;// equate values pointed to
*y = *pt.y;
return *this;
}
// accessors - so values can be seen
float get_x(){ return *x; }
float get_y(){ return *y; }
};
void showPoint(Point2 pt)// for testing pass by value
{
cout << "pt = (" << pt.get_x() << ", " << pt.get_y() << ")\n";
}
int main()
{
Point2 ptA(3.0f, 4.0f), ptB;
cout << "ptA = (" << ptA.get_x() << ", " << ptA.get_y() << ")\n";
cout << "ptB = (" << ptB.get_x() << ", " << ptB.get_y() << ")\n";
ptB = ptA;// this would cause a crash without the operator= overload
showPoint(ptB);// to demonstrate that pass by value works OK now
cout << endl;
return 0;
}
|
produces the following output:
combo ctor called
combo ctor called
ptA = (3, 4)
ptB = (0, 0)
assignment operator called
COPY ctor called
pt = (3, 4)
destructor called
destructor called
destructor called
|
Can you see why each line in the output is produced?