Difference between initialisation and assignment?

A

Andy Lomax

Is there any difference between:

foo A = B;

and

foo A;
A = B;

Specifically, I have a case where B is a function call which returns a
templated class. The first case gives a syntax error, but the second
case works. It appears to work because the assignment calls a type
conversion operator for the templated class.

Thanks -

AL
 
K

Karl Heinz Buchegger

Andy said:
Is there any difference between:

foo A = B;

and

foo A;
A = B;

The first is initialization.
The second is assignment.

For intialization a constructor is used.
For assignment the op= is used.
 
J

Jai

For intialization(foo A = B;) a copy constructor is used.
For assignment(A = B;) the op= is used.


Jai
 
E

Earl Purple

class A
{
private:
int m_x;
public:
A( int x ) : m_x( x )
{
}
};

A a1 = 1; // should compile because constructor is not explicit
A a2; a2=2; // error. A does not have default constructor.

class B
{
private:
int m_x;
public:
B( int x ) : m_x( x )
{
}
B() : m_x(0)
{
}
};

const B b1=1; // should compile
const B b2; b2=2; // error, cannot assign b2 because it's const

class C
{
private:
int m_x;
public:
explicit C( int x ) : m_x( x )
{
}
B() : m_x(0)
{
}
};

C c1 = 1; // error, implicit cast
C c2; c2 = 2; // also an error
C c3( 3 ); // correct
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top