Hi everyone,
Could someone tell us why the below code compiles and works? Is it
legal in the constructor of class B?
Cheers
Ronny
---------------------------------
#include <iostream>
using namespace std;
class a {
int x;
public:
void show() { cout<<x<<endl; }
a(int xx) : x(xx) {}
a() {}
};
class B {
a ma;
public:
B(int xx);
void disp() { ma.show(); }
};
B::B(int xx) {
ma = a(xx);
}
int main() {
B b(3);
b.disp();
return 0;
} 6 2494
rona wrote: Could someone tell us why the below code compiles and works?
Probably because it's well-formed...
Is it legal in the constructor of class B?
Yes, why do you ask? What throws you off?
---------------------------------
#include <iostream>
using namespace std;
class a { int x; public: void show() { cout<<x<<endl; } a(int xx) : x(xx) {} a() {} };
class B { a ma; public: B(int xx); void disp() { ma.show(); } };
B::B(int xx) { ma = a(xx);
This is an assignment from a temporary 'a' object (which is in turn
initialised from the 'xx') to the member 'ma'.
}
You could achieve the same effect by doing
B::B(int xx) {
ma = xx;
}
or, even better, by
B::B(int xx) : ma(xx) {
}
int main() { B b(3); b.disp(); return 0; }
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
rona wrote: Hi everyone,
Could someone tell us why the below code compiles
Yes, because there are no compile-time errors.
and works?
That's harder to determine. What are the requirements for the program?
Is it legal in the constructor of class B?
Yes. See below. Cheers
Ronny
---------------------------------
#include <iostream>
using namespace std;
class a { int x; public: void show() { cout<<x<<endl; } a(int xx) : x(xx) {} a() {}
This is bad because x is left unitialized and could remain so if the
user isn't careful. You probably added it so class B would compile.
};
class B { a ma; public: B(int xx); void disp() { ma.show(); } };
B::B(int xx) { ma = a(xx); }
This is legal, but you should delete the default constructor for class
a and use an initialization list here (see http://www.parashift.com/c++-faq-lit...html#faq-10.6). It works
because there is an implicit = operator generated for class a, and you
"convert" the integer xx to an "a" object by creating a temporary
object of type a. (Actually, it would also work if the line read "ma =
xx;" since that same constructor would be called implicitly.)
Cheers! --M
Victor Bazarov wrote: rona wrote: Could someone tell us why the below code compiles and works? Probably because it's well-formed...
Is it legal in the constructor of class B?
Yes, why do you ask? What throws you off?
Couple of reasons:
1- I knew using a constructor initializer list was the best option.
Eckel's book sounded as if it was the ONLY option. My mistake.
2- Still confused about what happens to the initial storage allocated
to the member ma. When ma is first declared within the class definition
for B, is memory allocated to ma. If yes, what happens to this memory
after "ma = a(xx);" ?
Cheers ---------------------------------
#include <iostream>
using namespace std;
class a { int x; public: void show() { cout<<x<<endl; } a(int xx) : x(xx) {} a() {} };
class B { a ma; public: B(int xx); void disp() { ma.show(); } };
B::B(int xx) { ma = a(xx);
This is an assignment from a temporary 'a' object (which is in turn initialised from the 'xx') to the member 'ma'.
}
You could achieve the same effect by doing
B::B(int xx) { ma = xx; }
or, even better, by
B::B(int xx) : ma(xx) { }
int main() { B b(3); b.disp(); return 0; }
V -- Please remove capital 'A's when replying by e-mail I do not respond to top-posted replies, please don't ask
rona wrote: Victor Bazarov wrote:
rona wrote: Could someone tell us why the below code compiles and works? Probably because it's well-formed...
Is it legal in the constructor of class B?
Yes, why do you ask? What throws you off?
Couple of reasons: 1- I knew using a constructor initializer list was the best option. Eckel's book sounded as if it was the ONLY option. My mistake.
No big deal. Happy to help.
2- Still confused about what happens to the initial storage allocated to the member ma. When ma is first declared within the class definition for B, is memory allocated to ma. If yes, what happens to this memory after "ma = a(xx);" ?
Memory stays where it is. You have a default c-tor in 'a' which leaves
the 'x' member uninitialised. Just before this statement, 'ma.x' has
indeterminate value (you can examine it in the debugger). Here, two
things happen: a temporary is constructed with 'xx' as the constructor
argument, and the [compiler-generated] assignment operator is called
which invokes the assignment semantics on all members, which for you
means 'ma.x = sometemporaryob ject.x'
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
rona wrote: Hi everyone,
Could someone tell us why the below code compiles and works? Is it legal in the constructor of class B?
Cheers
Ronny
---------------------------------
#include <iostream>
using namespace std;
class a { int x; public: void show() { cout<<x<<endl; } a(int xx) : x(xx) {} a() {} };
class B { a ma; public: B(int xx); void disp() { ma.show(); } };
B::B(int xx) { ma = a(xx); }
int main() { B b(3); b.disp(); return 0; }
Use
B::B(int xx): ma(xx) {
}
instead.
you are assigning a temporary object otherwise.
rona wrote: ... 1- I knew using a constructor initializer list was the best option. Eckel's book sounded as if it was the ONLY option. My mistake.
It would be the only option if class 'a' had no default constructor. But
it does have one.
If you remove the default constructor declaration from 'a' (the 'a() {}'
line), the code will no longer compile and a constructor initializer
list will become the only option of initializing 'ma' from 'B'.
2- Still confused about what happens to the initial storage allocated to the member ma. When ma is first declared within the class definition for B, is memory allocated to ma.
Yes, it is allocated. Initialization of that 'b' object begins with the
implicit initialization of 'ma' through a call to the default
constructor of class 'a' (mentioned above). The default constructor of
'a' does nothing, i.e. no physical initialization takes place ('ma'
still contains garbage after it), but conceptually 'ma' is "initialize d".
If yes, what happens to this memory after "ma = a(xx);" ?
A temporary object of type 'a' is created and initialized with the
'a::a(int)' constructor. Then this temporary object is copied into 'ma'
using the copy assignment operator 'a& a::operator=(co nst a&)'. Since
you didn't declare this operator explicitly, the compiler will declare
and define it for you implicitly.
--
Best regards,
Andrey Tarasevich This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jacek Dziedzic |
last post by:
Hi!
A) Why isn't it possible to set a member of the BASE class in
an initialization list of a DERIVED class constructor (except for
'calling' the base constructor from there, of course)? I even
tried prefixing them with BASE:: but to no avail. Still it's
ok when I set them in the construtor body, not the init list.
Does this mean that it's a small advantage of the initialization
inside the constructor over initialization in the init...
|
by: JustSomeGuy |
last post by:
I have a class that has a static member variable.
string x;
x should never change during use and should be intialized to "abcd".
How does one do this?
|
by: Jef Driesen |
last post by:
Hello,
Suppose I have a class that looks like this:
class point {
protected:
unsigned int m_x, m_y; // OR unsigned int m_data;
public:
point();
point(unsigned int x, unsigned int y);
|
by: Tony Johansson |
last post by:
Hello!
I'm reading in a book about C++ and there is something that I want to ask
you about.
It says "since the constructor does not return any value, the only way to
handle errors that
occur during its execution is to use exception handling. You can deal with
errors
that occur during the execution of the constructor's body by using try block
|
by: mnowosad |
last post by:
As far I know, static variables are tied to AppDomain scopes. So, every time
an executing code within an AppDomain references a class for the the first
time since the AppDomain was created/loaded, the .NET executes the
assignments done in the class static variables declarations and runs the
static constructor of that class.
So, I expected that, as in ASP.NET web site, for a given Web Service site,
the AppDomain would be initialized upon...
| |
by: Sandro Bosio |
last post by:
Hello everybody, my first message on this forum. I tried to solve my issue by reading other similar posts, but I didn't succeed. And forgive me if this mail is so long.
I'm trying to achieve the following (with incomplete succes): I want in a given namespace Parameters a list of "initializers" (which are objects derived from a simple interface that can be implemented anywhere, and are used to define which parameters the program will take at...
|
by: Jess |
last post by:
Hello,
I understand the default-initialization happens if we don't initialize
an object explicitly. I think for an object of a class type, the
value is determined by the constructor, and for the built-in types,
the value is usually garbage. Is this right?
However, I'm a bit confused about value-initialization, when does it
happen, and what kind of values are assigned to objects?
|
by: Jess |
last post by:
Hello,
I tried several books to find out the details of object
initialization. Unfortunately, I'm still confused by two specific
concepts, namely default-initialization and value-initialization. I
think default-init calls default constructor for class objects and
sets garbage values to PODs. Value-init also calls default
constructor for class objects and sets 0s to POD types. This is what
I've learned from the books (especially...
|
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 happens here
Suppose we have a function
void fn(Test arg);
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |