|
From: Ioannis V. <no...@ya...> - 2001-10-21 13:13:01
|
-----Original Message-----
From: Jason Hardman [mailto:jas...@bt...]=20
Sent: Sunday, October 21, 2001 2:00 PM
To: Ioannis Vranos
Subject: Re: [Dev-C++] Strange effect
>It seems you don't understand what I am explaining. Do you believe that
each time you create an object of a particular class you are=20
>recreating a set of methods specifically for that object? Or=20
Yes, when we create an object all member functions are being (re)created
for that particual object.
>do you believe that there are only a single set of methods for every
object of a type, and the objects only contain the data?=20
No.
>Note that there is a distinction between an object and a class. When
you report the size of the A and C objects note that A is 1 byte
>and C is 2 bytes, which is constistent with the two char's that are
declared. If a method code was also part of the object then the values=20
>would be much bigger.
>
>Note that you are actualy over running the A object in your code and
accessing undefined memory when you access b, but it doesn't=20
>cause any errors because of the way memory is managed by the compiler.
I expect that if larger data was used then problems would=20
>crop up.
Nope, because the whole thing is a compiler defect.=20
>I might try again to get across the idea again later, because I still
think it aproaches the truth of the situation. If you want you can=20
>report the error to the team that develop gcc and see what they say,
they will know better than either of us.
>I'm sure we'll discuss this some more but I'll leave it there for now.
What happens here is that the compiler creates a C object at the place
of the A object. That is a mess and here is the proof. Run this code to
see yourself!:
#include <iostream>
=20
class A
{
public:
char a;
void test() { a=3D'A'; }
};
=20
class C: public A
{
public:
char b;
void test() { a=3D'C'; b=3D'D'; }
};
=20
=20
=20
int main()
{
using namespace std;
=20
A a;
=20
C *cp=3Dstatic_cast<C *>(&a);
=20
cp->test();
=20
cout<<"a=3D "<<cp->a<<" b=3D "<<cp->b<<endl;
=20
cout<<"sizeof(a)=3D "<<sizeof(a)<<" sizeof(*cp)=3D =
"<<sizeof(*cp)<<endl;
cout<<"Address of a=3D "<<&a<<" Address of *cp=3D "<<cp<<endl;
}
It outputs:
C:\c>temp
a=3D C b=3D D
sizeof(a)=3D 1 sizeof(*cp)=3D 2
Address of a=3D 0x241ff5f Address of *cp=3D 0x241ff5f
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
|