Find the answer to your Linux question:
Results 1 to 4 of 4
I want to undestand following problem... I have a code: struct INT { }; struct LP { LP(const INT &p); LP& operator=(const INT &p); }; struct P { operator INT ...
  1. #1
    Just Joined!
    Join Date
    Apr 2009
    Posts
    2

    g++ copy-constuctor

    I want to undestand following problem... I have a code:
    struct INT
    { };

    struct LP
    {
    LP(const INT &p);
    LP& operator=(const INT &p);
    };

    struct P
    {
    operator INT () const;
    };

    int main()
    {
    P pi1;
    LP lpi2(pi1); // OK
    LP lpi2_ = pi1; // FAILS!
    lpi2 = pi1; // OK
    }
    in '//FAILS!' string i have compilation error in g++ (4.1.3). but i don't undestand why? can somebody help me how to fix stuctures to successfully compilation this (line) line without changes it (it - line with // FAILS comment)?

  2. #2
    Just Joined!
    Join Date
    Apr 2009
    Posts
    2
    maybe all sleep yet.. okey, i'm go sleep too, check answers tomorrow

  3. #3
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    LP lpi2_ = pi1; // FAILS!

    lpi2 = pi1; // OK

    The first one is a constructor of sorts and the second one is the equals operator which you just happen to have defined...G4143

    Code:
    struct INT
    {
    
    };
    
    struct LP
    {
    	LP(const INT &p);
    	LP& operator=(const INT &p);
    };
    
    struct P
    {
    	operator INT () const;
    };
    
    int main()
    {
    	P pi1;
    	LP lpi2(pi1); // OK
    	//LP lpi2_ = pi1; // FAILS!
    	lpi2 = pi1; // OK
    }
    Actually the lines you have marked OK are not. When you rem out the troubling line you get a whole bunch of new compiler errors...

    Why are you using structures for what is clearly classes?...Gerard4143
    Make mine Arch Linux

  4. #4
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    This is not allowed by the current C++ standards. To use an implicit copy constructor, such as you are doing ,where the value on the RHS of the assignment is a type which has to be used to construct a temporary of the class you are trying to copy, is not allowed. IE:

    LP lpi2(pi1);

    is allowed, as you are not using the assignment operator.
    as is this:

    LP lpi2_ = LP(pi1);

    as you are constructing an LP object explicitly, But,

    LP lpi2_ = pi1;

    is not allowed. The gnu compilers are very standards-aware these days, and this will, as you have seen, generate an error.
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...