Class constructor and C ++ / GCC object initialization / initialization

I am having problems with a C ++ class constructor using GCC.

The class "foo" is supposed to emulate a processor case, such as AL, AH, AX, EAX, ... and I need to have some basic arithmetic associated with this class. but I have weird behavior in the initialization or in the "foo" object.

I do not have the same result for the following two cases:

  foo w = 0x12345678;  // case 1

 foo w;  // case 2 init (2 steps)
     w = 0x12345678;

For me, case 2 works. GCC calls foo () (constructor 1), then the = operator. In the end, w.m_val is fine. But for case 1, GCC calls directly foo (long *) (constructor 2) and nothing else. Obviously not what I expect.

If "foo" where char, int or long, the result will be the same for both cases.

I may have misunderstood something about the designers or did something wrong. Can someone help me?

Thanks.

  class foo
 {
     public:
         foo () {// constructor 1 
           m_val = 0;
           m_ptr = NULL;
           };

         foo (long * p) {// constructor 2, should never be called !!!
           m_val = 0;
           m_ptr = p;
         };
         friend foo operator + (const foo & rhs, const unsigned int v);

         foo & operator + = (unsigned int v)
         {
             m_val + = v;
             return * this;
         }

         ~ foo () {};

          foo & operator = (const foo & rhs)
          {
             m_val = rhs.m_val;
             return * this;
          };
          foo & operator = (const unsigned int v)
          {
             m_val = v;
             return * this;
          };

     private:
         unsigned int m_val;
         long * m_ptr;
 };

+4
source share
1 answer

You misunderstand something about designers. Despite the visibility, foo w=0x12345678; does not contain assignment statement calls. This is copy-initialization and the (mostly) equivalent:

 foo w{foo{0x12345678}}; 

This should not compile because foo does not have a constructor that accepts an int parameter.

I say "mostly" because foo w=0x12345678; requires an implicit conversion from int to foo (or a subclass of foo ), where foo w{foo{0x12345678}}; enables explicit conversion and will never build a subclass of foo .

+3
source

Source: https://habr.com/ru/post/1446617/


All Articles