473,466 Members | 1,456 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Setting member variables before constructor call

Is the program at the end a correct C++ program?

I ask because the output is:

B::operator A&()
A::A()
B::B()
B::~B()
A::~A()

that means the casting operator which sets the
member variable B::p is called before the constructor
of B.
Here the program:
#include <iostream>

using std::cout;

struct A
{
A(){ cout <<"A::A()\n"; }
~A(){ cout <<"A::~A()\n"; }
};

struct B
{
B() // : p(0) // this kills the desruction of p
{ cout <<"B::B()\n"; }

~B()
{
cout <<"B::~B()\n";
delete p;
}

A* p;

operator A&()
{
cout <<"B::operator A&()\n";
p = new A;
return *p;
}
};

struct C
{
A& a;
B b;

C() : a(b) {}
};

int main()
{
C* c = new C;
delete c;

#if defined(__BORLANDC__) || defined(_MSC_VER)
system("PAUSE");
#endif

}

Jan 16 '06 #1
6 1987
sy*********@yahoo.com wrote:
Is the program at the end a correct C++ program?
A member function is called for an object whose lifetime hasn't started
yet because it's not been constructed. The storage the object occupies
is already create at that time. A pointer to that storage can be used,
but that use is limited. Dereferencing that pointer to access any member
of the object causes the program to have undefined behaviour. In your
case you attempt to assign the 'p' member inside B::operator A&(). Due
to that, your program has undefined behaviour.

It is a correct C++ program whose behaviour is undefined.
I ask because the output is:

B::operator A&()
A::A()
B::B()
B::~B()
A::~A()

that means the casting operator which sets the
member variable B::p is called before the constructor
of B.
Here the program:
#include <iostream>

using std::cout;

struct A
{
A(){ cout <<"A::A()\n"; }
~A(){ cout <<"A::~A()\n"; }
};

struct B
{
B() // : p(0) // this kills the desruction of p
{ cout <<"B::B()\n"; }

~B()
{
cout <<"B::~B()\n";
delete p;
}

A* p;

operator A&()
{
cout <<"B::operator A&()\n";
p = new A; ^^^^
This is the cause of the undefined behaviour.
return *p;
}
};

struct C
{
A& a;
B b;

C() : a(b) {}
It is generally a BAD IDEA(tm) to use uninitialised or only partially
constructed objects in the constructor initialisation list.
};

int main()
{
C* c = new C;
delete c;

#if defined(__BORLANDC__) || defined(_MSC_VER)
system("PAUSE");
#endif

}


V
Jan 16 '06 #2
I've assumed such a answer.
One way to circumvent the undefined behaviour is to use inheritance,
but is there a way to initialize the refernce without using
inheritance?
Peter

Jan 16 '06 #3

Victor Bazarov schrieb:
A member function is called for an object whose lifetime hasn't started
yet because it's not been constructed. The storage the object occupies
is already create at that time.


But why is it then dangerous to use this storage?

Jan 16 '06 #4
sy*********@yahoo.com wrote:
I've assumed such a answer.
One way to circumvent the undefined behaviour is to use inheritance,
but is there a way to initialize the refernce without using
inheritance?


I think you need to rearrange the members. Your 'b' will have been
already initialised at the time when you initialise 'a'.

V
Jan 16 '06 #5
sy*********@yahoo.com wrote:
Victor Bazarov schrieb:
A member function is called for an object whose lifetime hasn't started
yet because it's not been constructed. The storage the object occupies
is already create at that time.

But why is it then dangerous to use this storage?


"Use" is a very vague term. What do you mean by "use"? It's allowed to
pass the pointer to that storage elsewhere, and even store that pointer
in another object, for example, since the storage is not going away. I
don't want to quote the entire subclause of the standard, if you want to
see what is disallowed, please look at "3.8 Object Lifetime".

If you'd like a speculation on the subject of possible problems you can
run into, then imagine that you're trying to access a member of a class
that adjusts its own layout when initialising. There is no layout at all
when an object is still under construction, even if the compiler will let
you access a member, it's possible that the address (or the offset) it
will use is incorrect since the initialisation proper hasn't yet been
completed. So, you'll write something in the wrong place where it either
gets overridden or worse where your action overrides some other value,
which the program needs. That's just one example.

V
Jan 16 '06 #6
It depends on the declaration order:

B b;
A& a;

solves the problem.

Jan 16 '06 #7

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

Similar topics

4
by: baumann | last post by:
hi all, according the private / protected access control, - private; that is, its name can be used only by members and friends of the class in which it is declared. - protected; that is,...
4
by: Xavier | last post by:
Hi, I have a question, in a "dreaded diamond" situation, regarding the following code: ---- Begin code #include <iostream> using namespace std;
6
by: Dan Huantes | last post by:
I was presented a problem today where a class had member variable that was an object of a templated class. The class wanted to instantiate the object as a private member variable and call a...
8
by: Altman | last post by:
I have a class that I want many others inherited off of. I have created a variable in the parent class that I want the inherited classes to set. But I do not want to set the variable in the...
8
by: pauldepstein | last post by:
I am writing a program which looks at nodes which have coordinates which are time-dependent. So I have a class called node which contains the private member declarations int date; int month; ...
8
by: silversurfer2025 | last post by:
Hello everybody, I had this problem several times now and did not yet get the reasoning behind it. I have a class with a pointer as member variable, lets say a float array. Furthermore, I have two...
114
by: Jonathan Wood | last post by:
I was just wondering what naming convention most of you use for class variables. Underscore, "m_" prefix, camel case, capitalized, etc? Has one style emerged as the most popular? Thanks for...
1
by: ITMozart | last post by:
I wrote this piece of code: class A { public A() { someMeth(); } public void someMeth() { out.println(entries); }
10
by: JosephLee | last post by:
In Inside C++ object Model, Lippman said there are four cases in which compile will sythesize a default constructor to initialize the member variables if the constructor is absent: 1. there is a...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
0
isladogs
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.