Mail Archives: djgpp/1999/01/19/09:20:45
I have put this on the newsgroup a couple of times but have had no joy.
This test program tries to enter 2 instances of Thing's derived classes,
Thing_a and Thing_b, into a vector of Things.
When it comes to reading the Things from the vector, the Thing
implementations of the functions are run instead of the Thing_a and
Thing_b ones. This is clearly not what is meant to happen.
Can you explain this phenomenon for me - I think there is something funny
going on in the compiler.
Cheers,
Matthew
#include<iostream>
#include<string>
#include<vector>
class Thing
{
public:
virtual int number() { return -50; }
virtual string str() { return "Base class str"; }
virtual void print() { cout << "Base class print"; }
};
class Thing_a : public Thing
{
public:
Thing_a( int num ) :
_number( num ) {};
int number() { return _number; }
string str() { return "Thing_a str"; }
void print();
private:
int _number;
};
void
Thing_a::print()
{
cout << _number << endl;
}
class Thing_b : public Thing
{
public:
Thing_b( const string str );
int number() { return -100; }
string str() { return *_string; }
void print();
private:
string *_string;
};
Thing_b::Thing_b( const string str )
{
_string = new string( str );
}
void
Thing_b::print()
{
cout << *_string << endl;
}
main()
{
vector < Thing > thingVec;
Thing_a a( 50 );
string str = "bollox";
Thing_b b( str );
thingVec.push_back( a );
thingVec.push_back( b );
cout << "The number of things in the vec is: " << thingVec.size()
<< endl;
vector< Thing >::iterator iter;
for (iter = thingVec.begin(); iter != thingVec.end(); iter++)
iter->print();
int number = thingVec[ 0 ].number();
string str1 = thingVec[ 1 ].str();
cout << number << " " << str1 << endl;
cout << endl;
return( 0 );
}
Sanctus fortis, Sanctus Deus,
De profundis oro te,
Miserere, Judex Meus,
Parce mihi, Domine
http://www.cs.cf.ac.uk/User/M.P.Tidball/index.html
- Raw text -