Thread: Constructor calling another constructor

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    18

    Constructor calling another constructor

    Hi,

    In my code I have the following constructors for my class Point:

    Code:
    Point();
    Point(float x, float y, float z);
    The first, instantiates a point at the origin, and the other instantiates a point at the (x, y, z) coordinates. I've got a method called move(float x, float y, float z) that translates the point to the given coordinates.

    I've tried doing this:

    Code:
    Point(float x, float y, float z)
    {
            Point();
            move(x, y, z);
    }
    But it didn't work. So, how can I do it? Is it possible for a contructor to call another constructor like this?

    Thanks.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Try:
    Code:
    Point(float x, float y, float z) : Point()
    {
            move(x, y, z);
    }

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by rags_to_riches View Post
    Try:
    Code:
    Point(float x, float y, float z) : Point()
    {
            move(x, y, z);
    }
    That doesn't work yet, but it will soon, once it gets accepted into the next revision of the C++ standard. For now you have to write a function which is called by both constructors (though then you're actually doing assignment instead of initialisation), or just duplicate the code.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Well, I guess that shows how long it's been since I've been in Cplusplusland! Too long in Csharpistan rots the brain I suppose

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    18
    ...just duplicate the code.
    Yeah, I believe that's the best solution available. Thanks.

    renanmzmendes

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-10-2008, 08:38 PM
  2. C++ have a constructor call another constructor
    By QuestionC in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2007, 01:59 AM
  3. Replies: 3
    Last Post: 03-26-2006, 12:59 AM
  4. How do I override constructor in inheritance?
    By Loduwijk in forum C++ Programming
    Replies: 13
    Last Post: 03-24-2006, 09:36 AM
  5. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 04:50 AM