0

Possible Duplicate:
c++ call constructor from constructor

How to do "self" (this) assignments in c++?

Java:

 public Point(Point p) {
        this(p.x, p.y);
    }

How would do this in C++?

Would it be similar only this->(constructor of point that takes x, constructor of point that takes y);?

0

3 Answers 3

8

In C++0x, you can use delegating constructors:

Point(const Point &p) : Point(p.x, p.y) { }

Note that no compiler has full support for C++0x yet; this particular feature is not yet implemented in G++.

In older versions of C++, you have to delegate to a private construction function:

private:
    void init(int x, int y) { ... }
public:
    Point(const Point &p) { init(p.x, p.y); }
    Point(int x, int y)   { init(x, y); }
Sign up to request clarification or add additional context in comments.

10 Comments

Though in this case it's probably not worth the hassle.
I don't get the comment about older versions. It was always a design error using init and similar functions.
Though be careful -- delegating constructors aren't implemented in g++ yet even with --std=c++0x. I didn't realize that for a while once...
@bdonlan -- I know about delegating constructors, I'm saying using init type of functions was always a bad design. In pre-C++0x, one would write a non-delegating ctor, like Point(const Point& p) : x(p.x), y(p.y) {} even when it means more typing.
@Gene, for trivial constructors, this works, but if you're doing anything overly complex in the constructor, it may be justified to factor it out into a common function. It always depends on circumstances, then.
|
2

If I understand what you mean by this Java code (a constructor that relies on another constructor of the same class to do the job):

public Point(Point p) {
    this(p.x, p.y);
}

this is how I would express the same in C++:

class Point {

    Point(const Point& p)
       : Point(p.x, p.y) 
    {
        ...
    }
};

Comments

0

If you call another constructor of the same class it will create a new object.

If you want to do this, you should put the constructor logic in an init method and call it from all constructors.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.