[comp.lang.c++] C++ questions on Zortech and g++

yhe@zip.eecs.umich.edu (Youda He) (02/06/90)

// Here is a test program, I compiled it on sun4 use g++ 1.36.4
// on PC use zortech 2.01 (Still haven't get update).
// On PC Zortech report "Heap is corrupted"
// g++ will not compile for Vector class member access BaseVector
// protected member function/variable.
// after I made entire BaseVector public, it compiled ok, and the output
// list at the end, program compiled by both compiler give similar result,
// Both looks not right!
// so please some one has other compiler (AT&T 2.0) give it a try?

#ifdef __ZTC__
#include <stream.hpp>
#else
#include <stream.h>
#endif

class BaseVector {

  public: // inorder to compile on g++, declear everybody public;
   	  // to compile on PC remove these two lines.

//protected: // original protected:
  double *vector_ptr;
  int len;
  BaseVector(int len=10);
 
//public:    // public:
  ~BaseVector();
  double & operator[](const int index);
  friend ostream& operator << (ostream&, BaseVector&);
};

class Vector : public BaseVector {
  public:
  Vector(int len=10):(len) {}
  ~Vector()            {}
  BaseVector operator + (const Vector&);
};

BaseVector::BaseVector(int sz)
{
  vector_ptr = new double[len=sz];
  cout << "Base CTOR called " << (unsigned long) vector_ptr << "\n";
}

BaseVector::~BaseVector()
{
  cout << "Base DTOR called " << (unsigned long) vector_ptr << "\n";
  delete vector_ptr;
}

double & BaseVector::operator[](const int i)
{
  return *(vector_ptr+i);
}

BaseVector Vector::operator+(const Vector & x)
{
  BaseVector tmp(len);
  for(int i=0; i<len; i++) tmp.vector_ptr[i] = vector_ptr[i] + x.vector_ptr[i];
  return tmp;
}
ostream& operator<<(ostream& out, BaseVector& a)
{
  for(int i=0; i<a.len; i++)
    out << a[i] << " ";
  out << "\n";
}

int main(int argc, char *argv[])
{
  Vector a(20);
  for(int i=0; i<20; i++) a[i] = (double) i;
  cout << a;

  Vector b(20);
  for(i=0; i<20; i++) b[i] = (double) 2*i+1;
  cout << b;

  cout << a+b;
}
// Here are the output from sun4:

Base CTOR called 100520
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
Base CTOR called 100696
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 
Base CTOR called 100872
Base DTOR called 100872 <<=
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 
Base DTOR called 100872 <<= this destructor called twice!, Zortech report
			    Heap corrupted at this point, they call it twice
			    also.
Base DTOR called 100696
Base DTOR called 100520

Could some one tell me where I am wrong? since both compiler behaved
exactly the same, It is not likely they have exact same bug.

As to access protected member function/variable, I believe Zortech is correct:
I can access protected member function, if I am member of a derived class.


thanks

-- Youda --