🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.g++
Article #157

Class derivation and pointers

#157
From: Naoki Saito (GEO-002) Ext. 5471
Date: Wed, 04 Oct 1989 15:31
91 lines
2290 bytes
	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)
}
Technical Details
Message-ID: <8910041531.AA05591@ascsu1.SLCS.SLB.COM>
Path: arc1-ca.pugleaf.net!utzoo!telly!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!shelby!apple!gem.mps.ohio-state.edu!rpi!tut.cis.ohio-state.edu!sdrvx2.sinet.slb.com!saito

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!telly!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!shelby!apple!gem.mps.ohio-state.edu!rpi!tut.cis.ohio-state.edu!sdrvx2.sinet.slb.com!saito
From: saito@sdrvx2.sinet.slb.com (Naoki Saito (GEO-002) Ext. 5471)
Newsgroups: gnu.g++
Subject: Class derivation and pointers
Message-ID: <8910041531.AA05591@ascsu1.SLCS.SLB.COM>
Date: 4 Oct 89 15:31:37 GMT
Sender: daemon@tut.cis.ohio-state.edu
Distribution: gnu
Organization: GNUs Not Usenet
Lines: 91