473,394 Members | 2,031 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Understanding Initialization Syntax

When you initialize a variable like this:

X var;
var = X();

The equals sign is called the assignment operator and you can overload
it and indeed should in many cases.

However, when you write code like this:

X var = X();

What is the equals sign considered? Is it still an operator? Can you
overload it? I can't imagine any reason why you would want to overload
it, just curious.

Also, it is my current understanding this is what happens under the
hood in these cases. Could someone confirm I understand correctly?

First Case:
1) Allocate memory for an "X" variable.
2) Call default constructor for "X" and put that in "var" (no copy
right?).
3) Call default constructor of "X" again and copy it to "var".
4) Delete temp data from second call to default constructor (not sure
when that happens).

Second Case:
1) Allocate memory for an "X" variable.
2) Call default constructor for "X" and put it in var.

Thanks,

Joe
Jul 21 '08 #1
5 1299
joer3 wrote:
When you initialize a variable like this:

X var;
var = X();

The equals sign is called the assignment operator and you can overload
it and indeed should in many cases.

However, when you write code like this:

X var = X();

What is the equals sign considered? Is it still an operator? Can you
overload it? I can't imagine any reason why you would want to overload
it, just curious.
Copy constructor, it's easily overloaded, and you should be able to
think of many cases when you'd want to.
Jul 21 '08 #2
On Jul 21, 6:54*pm, Noah Roberts <u...@example.netwrote:
joer3 wrote:
When you initialize a variable like this:
X var;
var = X();
The equals sign is called the assignment operator and you can overload
it and indeed should in many cases.
However, when you write code like this:
X var = X();
What is the equals sign considered? Is it still an operator? Can you
overload it? I can't imagine any reason why you would want to overload
it, just curious.

Copy constructor, it's easily overloaded, and you should be able to
think of many cases when you'd want to.
Sorry for being unclear but I get what a copy constructor is and what
it's used for. When I did a little test to better understand this, I
didn't get consistent results with your statement. This program:

#include <iostream>

using namespace std;

class My_Class
{
public:
My_Class ()
{
cout << "I'm Default\n";
}

My_Class (const My_Class&)
{
cout << "I'm Copy\n";
}

My_Class& operator=(const My_Class)
{
cout << "I'm Assignment\n";
return *this;
}
};

int main()
{
cout << "My_Class a = My_Class():\n";
My_Class a = My_Class();

cout << "\nMy_Class b = a:\n";
My_Class b = a;

cout << "\na=b\n";
a = b;

return 0;
}

I get:

My_Class a = My_Class():
I'm Default

My_Class b = a:
I'm Copy

a=b
I'm Copy
I'm Assignment
Press any key to continue . . .

I am guessing My_Class a = My_Class() doesn't call copy constructor
because the compiler is trying to optimize right (FAQ [10.9])? Maybe
if you could overload the "=" you could force it to call the copy
constructor or do something else (again why would you want to).

That brings me back to my original question, if the "=" isn't an
operator what is it and can you overload it?
Jul 21 '08 #3
joer3 wrote:
[..] When I did a little test to better understand this, I
didn't get consistent results with your statement. This program:

#include <iostream>

using namespace std;

class My_Class
{
public:
My_Class ()
{
cout << "I'm Default\n";
}

My_Class (const My_Class&)
{
cout << "I'm Copy\n";
}

My_Class& operator=(const My_Class)
{
cout << "I'm Assignment\n";
return *this;
}
};

int main()
{
cout << "My_Class a = My_Class():\n";
My_Class a = My_Class();

cout << "\nMy_Class b = a:\n";
My_Class b = a;

cout << "\na=b\n";
a = b;

return 0;
}

I get:

My_Class a = My_Class():
I'm Default

My_Class b = a:
I'm Copy

a=b
I'm Copy
I'm Assignment
Press any key to continue . . .

I am guessing My_Class a = My_Class() doesn't call copy constructor
because the compiler is trying to optimize right (FAQ [10.9])?
Correct.
Maybe
if you could overload the "=" you could force it to call the copy
constructor or do something else (again why would you want to).

That brings me back to my original question, if the "=" isn't an
operator what is it and can you overload it?
(a) The '=' sign between the variable name and the initialiser in the
declaration statement is simply part of the syntax. It's not an
operator that you (or anybody else) can overload.

(b) There is no way to force a copy-constructor where it is allowed to
be forgone, using standard constructs. Perhaps you can do it using your
compiler's extensions/implementation-specific behaviours, but not using
any general language element.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 21 '08 #4
On Jul 22, 8:31 am, joer3 <joery...@gmail.comwrote:
a=b
I'm Copy
I'm Assignment
Press any key to continue . . .
Note: you see both "I'm..." messages here because you forgot to make
the assignment operator take the right-hand-side value by reference.
I am guessing My_Class a = My_Class() doesn't call copy constructor
because the compiler is trying to optimize right (FAQ [10.9])?
Didn't check FAQ reference, but yeah.
Maybe
if you could overload the "=" you could force it to call the copy
constructor or do something else (again why would you want to).
Nope... this is one very special case where the language is allowed to
bypass your assignment operator to call the constructor: you can't
prevent this optimisation.
That brings me back to my original question, if the "=" isn't an
operator what is it and can you overload it?
As mentioned above, "=" can simply be an (arguably) more readable
notation for construction, but for efficiency and so that it can be
supported when no default constructor is available, the optimisation
mentioned above is explicitly allowed to the compiler.

Working backwards, I'll address some of your original questions:
However, when you write code like this:
X var = X();
What is the equals sign considered? Is it still an operator? Can you
overload it? I can't imagine any reason why you would want to overload
it, just curious.
The equals sign is just a part of the construction notation, and
doesn't constitute a call to the operator= member function.

Note too: X var = X() doesn't require creation of a separate X
instance that's then copied over or assigned into var: the (stack)
memory for var is simply and directly initialised as per the default
constructor.

Cheers,

Tony
Jul 22 '08 #5
On Jul 22, 12:44 am, joer3 <joery...@gmail.comwrote:
When you initialize a variable like this:
X var;
var = X();
The equals sign is called the assignment operator and you can
overload it and indeed should in many cases.
However, when you write code like this:
X var = X();
What is the equals sign considered?
Punctuation. In this case, it's not an operator, and can't be
overloaded.
Is it still an operator? Can you overload it? I can't imagine
any reason why you would want to overload it, just curious.
No and no.
Also, it is my current understanding this is what happens
under the hood in these cases. Could someone confirm I
understand correctly?
First Case:
1) Allocate memory for an "X" variable.
2) Call default constructor for "X" and put that in "var" (no copy
right?).
3) Call default constructor of "X" again and copy it to "var".
And copy assign it to var. There's an important difference:
copy assignment works on a fully constructed variable.
4) Delete temp data from second call to default constructor
(not sure when that happens).
The last two points would best be described as:

-- construct a temporary X using the default constructor,
-- copy assign it to var, using the assignment operator,
-- destruct the temporary.
Second Case:
1) Allocate memory for an "X" variable.
2) Call default constructor for "X" and put it in var.
Formally:
-- construct a temporary X using the default constructor,
-- copy it into var, using the copy constructor,
-- destruct the temporary
The standard explicitly authorizes the compiler to optimize out
the copy, however (and all that I know of do).

Your description would correspond to:
X var ;

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 22 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: cppaddict | last post by:
Is it possible to avoid using push_back repeatedly when initializing a vector? That is, is there a vector syntax that would be analogous to the following array initialization syntax: MyClass...
16
by: John Kelsey | last post by:
Back in the "old" days with C, I used to do something like... struct { char Description; float price; } Items = { {"Apple", 1.99}, {"Banana", 2.04}
49
by: Luke Meyers | last post by:
Lately I find myself increasingly preferring the practice of going ever-so-slightly out of my way to avoid the use of the form of initialization which uses the '=' symbol, on the grounds that it...
8
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it....
8
by: boki_pfc | last post by:
Hi Everybody, I am looking for an advice on following: I have that "pleasure" of reading C++ codes that have been written by person(s) that have not attended the same C++ classes that I did or...
11
by: subramanian100in | last post by:
Suppose we have a class named Test. Test obj; // assuming default ctor is available Test direct_init(obj); // direct initialization happens here Test copy_init = obj; // copy initialization...
3
by: mhvaughn | last post by:
struct S1 { int i; }; struct S2 { S1 s; // version 1 S2() {} ; // version 2
10
by: Juha Nieminen | last post by:
I suppose you can never know C++ fully. I would have never guessed this actually compiles and works: struct Point { int x, y; }; struct Line { Point endpoint; int weight; };
7
by: krishna | last post by:
What is the need of this syntax for initializing values, isn't this ambiguous to function call? e.g., int func_name(20); this looks like function call (of course not totally as there is no...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.