Overloading output stream and pure virtual functions
Aug 7, 2013 at 5:55pm UTC
Hey everyone.
I'm working with inheritance and pure virtual functions, and I want to overload an output stream operator. However, every time I run the program I get this: 0x7fff00ee98c0.
I'll include a base class and a derived class so you can see what I'm talking about.
Base:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
using namespace std;
#ifndef _Insurance_h_
#define _Insurance_h_
class Insurance {
protected :
string name;
float commission;
string salesperson;
public :
virtual void Commission() = 0;
string getName();
string getSalesperson();
float getCommission();
friend ostream& operator <<(ostream &strm, const Insurance& i) {
i.Print(strm);
return strm;
}
virtual void Print(ostream&) const = 0;
};
#endif
Derived:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef _Auto_h_
#define _Auto_h_
#include "Insurance.h"
class Auto : public Insurance {
private :
string make;
string model;
int VIN;
float liability;
float collision;
public :
Auto(string, string, string, string, int , float , float );
void Commission();
void Print(ostream&) const ;
};
#endif
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include "Auto.h"
Auto::Auto(string n, string sales, string make, string model, int VIN, float lia, float col) {
name = n;
salesperson = sales;
make = make;
model = model;
VIN = VIN;
liability = lia;
collision = col;
}
void Auto::Commission() {
commission = (liability + collision) * 0.3;
}
void Auto::Print(ostream &strm) const {
strm << "Auto - Name of insured: " << name << endl;
strm << "Make and model of car: " << make << ", " << model << endl;
strm << "VIN : " << VIN << endl;
strm << "Liability coverage: $" << liability << endl;
strm << "Collision coverage: $" << collision << endl;
strm << "Commission: $" << commission << endl;
}
The application is something like this (I'm assuming the user has already inputted the name, salesperson, make, model, etc):
1 2 3 4 5 6 7 8 9 10 11
#include "Auto.h"
#include <iostream>
using namespace std;
#include <vector>
vector<Insurance *> sales;
Auto a1(name, salesperson, make, model, VIN, liability, collision);
sales.push_back(&a1);
for (int i=0; i<sales.size(); ++i) {
cout << i << ". " << sales[i] << endl;
}
Last edited on Aug 7, 2013 at 5:56pm UTC
Aug 7, 2013 at 6:21pm UTC
You are storing pointers in the vector so sales[i]
will give you a pointer.
Aug 7, 2013 at 6:25pm UTC
How would I print the actual object? (still using overloaded operators and virtual functions)
Aug 7, 2013 at 6:35pm UTC
cout << i << ". " << *sales[i] << endl;
Aug 7, 2013 at 7:28pm UTC
I tried that, and the system printed this:
pure virtual method called
terminate called without an active exception
1. Aborted
Topic archived. No new replies allowed.