Initialization of object

R

Rahul

Hi Everyone,

I have the following code,

class A
{
public : A()
{
}
void show()
{
}
};


int main()
{
cout<<"Enter the number : ";
int n;
cin>>n;
if(n<10)
goto label;
A obj;
label:
obj.show();
return(0);
}

and i get the expected error saying "initialization of obj is skipped
by goto label". But when i remove the definition of the constructor
from the class, i don't the error, why is this so?

Thanks in advance ! ! !
 
J

joseph cook

and i get the expected error saying "initialization of obj is skipped
by goto label". But when i remove the definition of the constructor
from the class, i don't the error, why is this so?

Thanks in advance ! ! !

"A program that jumps from a point where a local variable
with automatic storage duration is not in scope to a
point where it is in scope is illformed unless the variable
has POD type (3.9) and is declared without an initializer
(8.5)."

A more interesting question might be why if you changed your
definition of show() to:


void show
{
std::cout<<"I got called!"<<std::endl;
}

You would see no output (no matter the user input). That doesn't
seem right to me...
 
D

David Côme

Hi Everyone,

I have the following code,

class A
{
public : A()
{
}
void show()
{
}
};


int main()
{
cout<<"Enter the number : ";
int n;
cin>>n;
if(n<10)
goto label;
A obj;
label:
obj.show();
return(0);
}

and i get the expected error saying "initialization of obj is skipped
by goto label". But when i remove the definition of the constructor
from the class, i don't the error, why is this so?

Thanks in advance ! ! !
NEVER USE GOTO !!
Do it :
int main()
{
cout<<"Enter the number : ";
int n;
cin>>n;
if(n<10)
{
A obj;
obj.show();
}
return(0);
}
 
J

James Kanze

I have the following code,
class A
{
public : A()
{
}
void show()
{
}
};
int main()
{
cout<<"Enter the number : ";
int n;
cin>>n;
if(n<10)
goto label;
A obj;
label:
obj.show();
return(0);
}
and i get the expected error saying "initialization of obj is
skipped by goto label". But when i remove the definition of
the constructor from the class, i don't the error, why is this
so?

Because you're declaring an uninitialized object, and
presumably, your code is capable of handling uninitialized
objects. (In this regard, an object is "initialized" if there
is explicit initialization, or the type of the object has a
non-trivial constructor.)

In real code (which doesn't use goto), this is still relevant in
switch statements, whose semantics is exactly that of a goto.
 

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

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top