Explicitly calling constructor

Discussion in 'C++' started by Kavya, Oct 29, 2006.

  1. Kavya

    Kavya Guest

    Suppose I have class MyClass. Then which will be termed as explicit
    call to constructor.

    MyClass( );

    or

    MyClass object;
    object.MyClass( );
    Kavya, Oct 29, 2006
    #1
    1. Advertising

  2. * Kavya:
    > Suppose I have class MyClass. Then which will be termed as explicit
    > call to constructor.
    >
    > MyClass( );
    >
    > or
    >
    > MyClass object;
    > object.MyClass( );


    The second line of the latter isn't valid code.

    The first is an example of what the standard calls an explicit
    constructor call, while the first line of the second example is a
    declaration with an implicit constructor call.

    Used as a stand-alone expression statement (some illuminating context
    would be nice!) "MyClass();" creates a temporary of MyClass type and
    calls the default constructor on that temporary.

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Oct 29, 2006
    #2
    1. Advertising

  3. Kavya wrote:
    > Suppose I have class MyClass. Then which will be termed as explicit
    > call to constructor.
    >
    > MyClass( );
    >
    > or
    >
    > MyClass object;

    When the object was declared,it was automatic initialized by calling
    class's contructor.
    > object.MyClass( );
    Osamede.Zhang, Oct 29, 2006
    #3
  4. Kavya:

    > MyClass( );



    That createless a nameless object which exists until the end of the
    statement. The following two snippets are equivalent:

    int main()
    {
    int i = MyClass().GetVal();
    }

    int main()
    {
    int i;

    {
    MyClass nameless_object;
    i = nameless_object.GetVal();
    }
    }

    If you would like to invoke a class's constructor, you need to supply it
    with a memory address at which to construct an object of the class in
    question. "Placement new" is used for this:

    void *const pmem = malloc(512);

    MyClass *const p = ::new((void*)pmem) MyClass();

    p->~MyClass();

    free(pmem);

    --

    Frederick Gotham
    Frederick Gotham, Oct 29, 2006
    #4
    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. daveb
    Replies:
    6
    Views:
    371
    Alf P. Steinbach
    Jul 17, 2006
  2. Replies:
    7
    Views:
    533
    Frederick Gotham
    Sep 8, 2006
  3. shsingh
    Replies:
    13
    Views:
    739
  4. Lawrence Spector
    Replies:
    3
    Views:
    291
    Kai-Uwe Bux
    Jul 16, 2007
  5. Generic Usenet Account
    Replies:
    10
    Views:
    2,217
Loading...

Share This Page