M
MSR
I have a couple of questions.
1. Copy Constructor.
class A {
private:
int a1;
double d1;
char *ptr;
public:
const A* operator=(const A* b)
{
memcpy(this, b, sizeof(A));
ptr = new char[100];
};
};
int main()
{
A *b = new b;
A *c=b;
.............
..........
};
Does C++ guarantee that my memcpy always make an exact duplicate of Object
'b' no matter how big the class is. Is this a general way of writing copy
constructors?
2. Null Reference. For example we have a function that searches a list and
returns a pointer to an object if it is found or NULL if it can't find the
object. How can I do this if I want to return a reference instead of a
pointer, without throwing exceptions?
3. This code is from FAQ lite.
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point:oint(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point:olar(float radius, float angle)
{ return Point(radius*cos(angle), radius*sin(angle)); }
int main()
{
Point p1 = Point::rectangular(5.7, 1.2); // Obviously rectangular
Point p2 = Point:olar(5.7, 1.2); // Obviously polar
...
}
Dumb question. Now who owns p1 and p2 and how can I delete them?
Thanks for your time and help
--MSR
1. Copy Constructor.
class A {
private:
int a1;
double d1;
char *ptr;
public:
const A* operator=(const A* b)
{
memcpy(this, b, sizeof(A));
ptr = new char[100];
};
};
int main()
{
A *b = new b;
A *c=b;
.............
..........
};
Does C++ guarantee that my memcpy always make an exact duplicate of Object
'b' no matter how big the class is. Is this a general way of writing copy
constructors?
2. Null Reference. For example we have a function that searches a list and
returns a pointer to an object if it is found or NULL if it can't find the
object. How can I do this if I want to return a reference instead of a
pointer, without throwing exceptions?
3. This code is from FAQ lite.
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point:oint(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point:olar(float radius, float angle)
{ return Point(radius*cos(angle), radius*sin(angle)); }
int main()
{
Point p1 = Point::rectangular(5.7, 1.2); // Obviously rectangular
Point p2 = Point:olar(5.7, 1.2); // Obviously polar
...
}
Dumb question. Now who owns p1 and p2 and how can I delete them?
Thanks for your time and help
--MSR