www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1995/04/05/06:12:49

Date: Wed, 5 Apr 1995 04:29:30 -0500 (CDT)
From: Scott McCaskill <jmccaski AT CS DOT Trinity DOT Edu>
To: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: problems w/virtual functions

Below is an example of the type of code that is giving me problems:

class Base
{
	int i;
public:
	virtual void print(ostream &);
	friend ostream & operator<<(ostream &, Base &);
};

void Base::print(ostream & out) { out << "Base::print()\n"; }

ostream & operator<<(ostream & out, Base & b)
{
	out << "operator<<(ostream &, Base &)\n";
	b.print(out);
	return out;
}


class Derived : public Base
{
	int j;
public:
	virtual void print(ostream &);
	friend ostream & operator<<(ostream &, Derived &);
};

void Derived::print(ostream & out)
{
	Base::print(out);
	out << "Derived::print()\n";
}

ostream & operator<<(ostream & out, Derived & d)
{
	out << "operator<<(ostream &, Derived &)\n";
	d.print(out);
	return out;
}


class Outside
{
public:
	Base * basep;
	virtual void print(ostream &);
	friend ostream & operator<<(ostream &, Outside &);
};

void Outside::print(ostream & out) { out << "Outside::print()\n"; out << 
*basep << endl; }

ostream & operator<<(ostream & out, Outside & o)
{
	o.print(out);
	return out;
}


void main()
{
	Outside o;
	Derived d;
	
	o.basep = &d;
	cout << o << endl;
}

/* should result in:

Outside::print()
operator<<(ostream &, Base &)
Base::print()
Derived::print()

*/

Now this particular example works...which is why I can't figure out why 
the code it's based on doesn't.  The problem is that Derived::print() 
never gets called (from the cout in main() for example) when a base 
class pointer (pointing to a derived class object) is used.  It just 
stops, or (usually when in a windows dos box) gives a GPF or segmentation 
fault.  Has anyone else encountered problems like this?  I'll keep 
looking, but the code above is highly representative of the actual code.

Thanks in advance for any assistance--
Scott

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Scott McCaskill
(jmccaski AT cs DOT trinity DOT edu)              http://www.cs.trinity.edu/~jmccaski/



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019