By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,943 Members | 1,875 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,943 IT Pros & Developers. It's quick & easy.

Difference between this TWO

P: 9
what is difference between these two ?

1.

class A
{
private:
int a;
int b;
public:
A(int i, int j)
{
a = i;
b = j;
}
};

2.

class A
{
private:
int a;
int b;
public:
A(int i, int j) : a(i), b(j)
{
}
};


can, any one explain it more....
Jun 13 '07 #1
Share this Question
Share on Google+
3 Replies


gpraghuram
Expert 100+
P: 1,275
HI,
The second example u have given is an example of constructor Argument list.
It is one of the best practices for coding in c++.
For info on it make a search and u will get it

Raghuram
Jun 13 '07 #2

P: 94
With an int in a normal C++ program, you can assign a value to the int by doing:
Expand|Select|Wrap|Line Numbers
  1. int a(5);
  2.  
The second one is just another way to assign values to private variables in a class. Same way as mentioned above
They are the same, just different syntax
Jun 13 '07 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
This is ot correct:
With an int in a normal C++ program, you can assign a value to the int by doing:

Code: ( text )
int a(5);

The second one is just another way to assign values to private variables in a class. Same way as mentioned above
They are the same, just different syntax
When you use a constructor initializer list, the values are placed in the data members as they are created. When you assign values to members inside the constructor, you are changing the value of a data member that already exists.

If your class has a const member:
Expand|Select|Wrap|Line Numbers
  1. class MyClass
  2. {
  3.     private:
  4.         const int MAX;
  5.     public:
  6.         MyClass();
  7. };
  8.  
the value of the MAX member must be placed in the member when it is created. Becuse of this, the code below will produce an error:

Expand|Select|Wrap|Line Numbers
  1. MyClass::MyClass()
  2. {
  3.     MAX = 10;   //ERROR. Cannot change a constant.
  4. }
  5.  
There will also be another error about creating a const without a value.

The way around this is the initializer list:

Expand|Select|Wrap|Line Numbers
  1. MyClass::MyClass() : MAX(10)
  2. {
  3. }
  4.  
Now the value 10 is used to initialize the MAX member when the MAX member is created.

You will also need the initializer list to call constructors for any base classes, or construtors for any contained class members.

Lastly, this is bad form:

Expand|Select|Wrap|Line Numbers
  1. int a(5);
  2.  
This code is equivalent to:
Expand|Select|Wrap|Line Numbers
  1. int a = static_cast<int> (5);
  2.  
This form of initialization is in C++ for template writers.
Jun 13 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.