Reference to class question

N

Nephi Immortal

Please confirm if my code is valid with no undefined behavior. When
you create data members, any built-in types such as char, int are
always uninitialized until you tell Constructor function to initialize
them.

What about two data members: x and y in Z class? Both x and y are
always initialized automatically with memory address before you call
Constructor function.

Reference is like a pointer to set up memory address. The y in Z
class is always bound to Y class and it can’t be unbound unless you
change from reference to pointer.

struct X
{
X( int _x, int _y ) : x( _x ), y( _y )
{
}

~X()
{
}

int x;
int y;
};

struct Y
{
Y( X& _x ) : x( _x )
{
}

~Y()
{
}

X &x; // reference
};

struct Z
{
Z( int a, int b ) : x( a, b ), y( x ) // initialized y( x )
{
}

~Z()
{
}

X x;
Y y;
};


int main()
{
Z z( 1, 2 );

return 0;

}
 
I

Ian Collins

Please confirm if my code is valid with no undefined behavior. When
you create data members, any built-in types such as char, int are
always uninitialized until you tell Constructor function to initialize
them.

What about two data members: x and y in Z class? Both x and y are
always initialized automatically with memory address before you call
Constructor function.

They aren't initialised with an address, they have an address. They are
part of the Z object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top