1

Possible Duplicate:
Why should I prefer to use member initialization list?

Class A has a member variable i. i can be initialized or assigned during object creation.

A) Initialise

   class A {
         int i;
    public:
        A(int _i) : i(_i){}
    }

B) assign

class A {
         int i;
    public:
        A(int _i) : { i = _i}
    }

My question is what is the basic difference between these 2 approach?

Community
  • 1
  • 1
user966379
  • 2,823
  • 3
  • 24
  • 30

1 Answers1

2

The difference lies in which C++ mechanism is used to initialize i in your class. Case (A) initializes it via constructor, and case (B) uses the assignment operator (or a copy constructor if no assignment operator is defined).

Most C++ compilers would generate exactly the same code for this particular example, because you're using int, which is a "plain old data" type. If i were a class type, it could make a great deal of difference.

David O'Riva
  • 696
  • 3
  • 5
  • at this point object has not been created so copy contr or assignment operator is not available here – user966379 Apr 13 '12 at 02:18
  • @user966379 - I was referring to the constructor or assignment operator for `i` alone, not `A`. Since `i` is of type `int`, the constructor or assignment operator for an `int` are used when initializing that particular member of your class, whether your entire class is ready yet or not. – David O'Riva Apr 13 '12 at 02:31