initialization on a struct member fails

P

Peter Liu

This simple code

typedef strt B{
int b;
}BS;

typedef struct A:B
{
int a;
int foo(){return a+b;}
}AS;

int main()
{
AS*pab=new AS();
pab->b=4;
pab->a=5;
pab->a=pab->foo();

***********//Output result is incorrect only 4 //***********

delete pab;
}

Why isn't the output 9 as it is supposed to be ?

Thanks
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

This simple code

typedef strt B{
int b;

}BS;typedef struct A:B
{
int a;
int foo(){return a+b;}

}AS;int main()
{
AS*pab=new AS();
pab->b=4;
pab->a=5;
pab->a=pab->foo();

***********//Output result is incorrect only 4 //***********

delete pab;

}Why isn't the output 9 as it is supposed to be ?

By converting it to C++ it works much better:

#include <iostream>

struct B{
int b;
};

struct A : public B
{
int a;
int foo(){return a+b;}

};

int main()
{
A* pab = new A();
pab->b=4;
pab->a=5;
std::cout << pab->foo();

delete pab;
}
 
G

Grizlyk

Peter said:
This simple code

typedef strt B{
? strt
int foo(){return a+b;}
It works ok
movl 8(%ebp), %eax
movl 4(%eax), %edx //b->%edx
movl 8(%ebp), %eax
movl (%eax), %eax //a->%eax
leal (%edx,%eax), %eax // a+b->%eax !!! look like add !!!
 
J

Jacek Dziedzic

Peter said:
This simple code

typedef strt B{
int b;
}BS;

typedef struct A:B
{
int a;
int foo(){return a+b;}
}AS;

int main()
{
AS*pab=new AS();
pab->b=4;
pab->a=5;
pab->a=pab->foo();

***********//Output result is incorrect only 4 //***********

delete pab;
}

Why isn't the output 9 as it is supposed to be ?

It is 9 on my system, after changing "strt" to
"struct" and adding an actual output statement.
That goes to show you haven't given us the actual
code that fails.

Also note that what you are doing is assignment,
not initialization.

- J.
 
P

Peter Liu

Jacek Dziedzic $B$N%a%C%;!<%8(B:
It is 9 on my system, after changing "strt" to
"struct" and adding an actual output statement.
That goes to show you haven't given us the actual
code that fails.

Also note that what you are doing is assignment,
not initialization.

- J.

Sorry everyone, it works correctly, my mistake hehehhe. :-(
 

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,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top