Re: initializer list of the struct

Discussion in 'C++' started by Thomas J. Gritzan, Oct 20, 2009.

  1. Johnson schrieb:
    > Johnson wrote:
    >> I would like to know if I initialize a struct, will the constructor
    >> function of the struct be called? Actually I found it didn't. I also
    >> get an error when I compile it.
    >> error C2552: 'perm_address' : non-aggregates cannot be initialized
    >> with initializer list
    >>
    >> Any recommendation to remove the error?
    >>
    >> Thank you!
    >>
    >> For example:
    >> struct address
    >> {
    >> int street_no;
    >> char *street_name;
    >>
    >> address (int street_no_,
    >> char *street_name_) //it is not called by the initializer
    >> {
    >> street_no = street_no_;
    >> street_name = new char (sizeof (street_name_)/sizeof(char));
    >> strcpy (street_name, street_name_);
    >> };
    >>
    >> ~address(void) { delete [] street_name; };
    >>
    >> };
    >>
    >> static struct address perm_address =
    >> { 3, "Savona Dr."}; //initize the struct

    >
    > Thank you for correcting my mistakes. My problem is now solved!


    I hope you solved the new-line problem, too:

    Wrong:
    street_name = new char (sizeof (street_name_)/sizeof(char));

    Correct:
    street_name = new char[ strlen(street_name_)+1 ];

    Better:
    Replace char* with std::string.

    --
    Thomas
    Thomas J. Gritzan, Oct 20, 2009
    #1
    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. M Kumar

    struct initializer { 0 }

    M Kumar, Sep 28, 2003, in forum: C Programming
    Replies:
    2
    Views:
    397
    Ivan Vecerina
    Sep 28, 2003
  2. Chris Fogelklou
    Replies:
    36
    Views:
    1,371
    Chris Fogelklou
    Apr 20, 2004
  3. Laurent Deniau

    struct initializer efficiency

    Laurent Deniau, Aug 28, 2007, in forum: C Programming
    Replies:
    0
    Views:
    265
    Laurent Deniau
    Aug 28, 2007
  4. Richard
    Replies:
    0
    Views:
    406
    Richard
    Oct 20, 2009
  5. xmllmx
    Replies:
    4
    Views:
    228
    Zhihao Yuan
    Dec 17, 2012
Loading...

Share This Page