简体   繁体   中英

class constructor and object instanciation/initialisation C++/GCC

I have troubles with a C++ class constructor, using GCC.

The class "foo", hereunder, is supposed to emulate a processor register like AL, AH, AX, EAX,... and i need to have some basic arithmetic associated with this class. but i have a strange behaviour in the initialisation or a "foo" object.

I don't have have the same result for the 2 following cases:

foo w=0x12345678; //  case 1

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

For me, case 2 is working GCC calls foo() ( constructor 1) then the = operator. At the end, w.m_val is ok But for case 1 GCC calls directly foo( long *) ( constructor 2) and nothing else. Obviously that's not what i'm expecting.

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

I maybe misunderstood something about constructors or did something wrong. Could somebody 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;
};

You are misunderstanding something about constructors. Despite appearances, foo w=0x12345678; does not contain any calls to an assignment operator. It is copy-initialization , and (mostly) equivalent to:

foo w{foo{0x12345678}};

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM