saito@sdrvx2.sinet.slb.com (Naoki Saito (GEO-002) Ext. 5471) (10/05/89)
Hello, folks! I'm using g++-1.34.2 on Sun3/60 with OS 4.0.1.
Suppose the class Y is derived from the class X. Then, consider the following
program segment.
X *px;
px = new Y();
In this case, px points to the object X or Y? And *px is considered as object
X or Y? I thought that px points to object Y and *px is considered as Y.
However, The following program confused me a lot. Especially, the last 4 lines:
px->mul_print(px1); => error at compilation time
px->mul_print(*px1); => works! *px1 is considered as X.
px->add_print(px1); => works! px1 is considered as Y, not the pointer to Y.
px->add_print(*px1); => error at run time. core dumps.
This is a bug of the g++-1.34.2? Or this is normal behavior and my programming
example is not appropriate? How does the AT&T C++ 2.0 handle these?
Thanks in advance,
Naoki Saito(saito@sdr.slb.com)
Schlumberger-Doll Research
=================================cut===========================================
#include <stream.h>
class X
{
protected:
float a;
public:
X();
X(float);
virtual void add_print(...){};
void mul_print(X&);
};
class Y : public X
{
protected:
float b;
public:
Y();
Y(float);
void add_print(Y&);
};
X::X()
{
a = 100.0;
}
X::X(float f)
{
a = f;
}
void X::mul_print(X& x)
{
cout << "mul_print of class X:" << a * x.a << "\n";
}
Y::Y() : ()
{
b = 10.0;
}
Y::Y(float f) : (f*2)
{
b = f;
}
void Y::add_print(Y& y)
{
cout << "add_print of class Y:" << a + b + y.a + y.b << "\n";
}
main()
{
X *px0, *px1;
px0 = new Y();
px1 = new Y(1.0);
// px0->mul_print(px1); error at compilation time.
px0->mul_print(*px1);
px0->add_print(px1);
// px0->add_print(*px1); error at run time. Bus error (core dumped)
}