Jump to content

int cl= 10 or int cl(10)

- - - - -

  • Please log in to reply
5 replies to this topic

#1
irancplusplus

irancplusplus

    Learning Programmer

  • Members
  • PipPipPip
  • 65 posts
hi
we have a class like this:

class int2

{

public:

	int2(int a)

	{

	}

};

are these two lines:
int2 s(10);
int2 s = 10;
completely equivalent in any C++ compiler & any compiler options?

Edited by irancplusplus, 06 February 2012 - 07:04 AM.

I wrote this ebook! Will you translate it into English for free!?:confused: PM me!

#2
untitled_1

untitled_1

    Learning Programmer

  • Members
  • PipPipPip
  • 89 posts
those two lines are the same thing

#3
DRK

DRK

    Newbie

  • Members
  • PipPip
  • 10 posts
Initialization by assignment operator = works only for 1-parameter constructor (like in your example). For constructor with more parameters only initialization by brackets () is possible.

#4
notes

notes

    Learning Programmer

  • Members
  • PipPipPip
  • 48 posts
Also constructors initialization list accepts only bracket version.
class int2 {

    int a;

    public :

    int2(int b) : a(b)  

    {    


    } 


};

In this case while creating new int2 object first compiler will make operations on initialization list then everything in braces { } .
Remebre about KISS & DRY

#5
DRK

DRK

    Newbie

  • Members
  • PipPip
  • 10 posts
EDIT: Never mind.

#6
kernelcoder

kernelcoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 282 posts
  • Location:Dhaka
  • Programming Language:C, Java, C++, C#, Visual Basic .NET
  • Learning:Objective-C, PHP, Python, Delphi/Object Pascal
class int2
{
};
If you write above code, compilers (as far as I know any compiler) will generate 3 things for you -- i) default constructor, ii) copy constructor and iii) assignment operator (overloading). So the generated code will be something like following...


class int2
{
public:
int2(){} // This is the reason you are able to write 'int2 i2;'
int2(const int2 &other) {} // This is the reason you are able to write 'int2 i1; int2 i2(i1); int2 i2=i1; '
int2 operator=(const int2& other){} // This is the reason you are able to write 'int2 i1; int2 i2; i2 = i1; '
};

However, if you define any constructor of your own, compiler will not generate default constructor. If you write copy constructor or copy assignment operator of your own, compiler will not generate them.

So, in your case, yes, 'int2 s(10);' and 'int2 s = 10;' are completely equivalent.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users