Re: How can a constructor call another contructor?

Discussion in 'C++' started by E. Robert Tisdale, Aug 26, 2003.

  1. sbmoon wrote:

    > There are two constructors on a class.
    >
    > How can a constructor call another constructor?


    class X {
    private:
    int I;
    public:
    X(int i): I(i) { }
    X(void) {
    *this = X(0); // calls X(int)
    }
    };

    This is the only way that a constructor can call another constructor.
     
    E. Robert Tisdale, Aug 26, 2003
    #1
    1. Advertising

  2. E. Robert Tisdale

    Ron Natalie Guest

    "E. Robert Tisdale" <> wrote in message news:...

    > *this = X(0); // calls X(int)
    > }

    Which really does't call the constructor directly, but constructs a temporary object with an integer
    argument and assigns it to the current.

    Of course, you'd better be darn sure that you've initialized everything that operator= might
    care about before you do this.
     
    Ron Natalie, Aug 26, 2003
    #2
    1. Advertising

  3. E. Robert Tisdale

    jeffc Guest

    "E. Robert Tisdale" <> wrote in message
    news:...
    > sbmoon wrote:
    >
    > > There are two constructors on a class.
    > >
    > > How can a constructor call another constructor?

    >
    > class X {
    > private:
    > int I;
    > public:
    > X(int i): I(i) { }
    > X(void) {
    > *this = X(0); // calls X(int)
    > }
    > };
    >
    > This is the only way that a constructor can call another constructor.


    A rather baroque way of merely showing how to create another object and
    "call" the constructor that way.
     
    jeffc, Aug 26, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jeffc
    Replies:
    0
    Views:
    698
    jeffc
    Aug 26, 2003
  2. Matt Graham
    Replies:
    3
    Views:
    528
    Matt Graham
    Feb 7, 2004
  3. Andy
    Replies:
    9
    Views:
    519
    Pete Becker
    Sep 24, 2006
  4. Generic Usenet Account
    Replies:
    10
    Views:
    2,323
  5. Warren Tang
    Replies:
    9
    Views:
    681
    James Kanze
    Apr 15, 2008
Loading...

Share This Page