Reputation: 122
I have created a class VehicleType
and bikeType
and want to overload stream insertion and extraction operator for derived class because I need to read data from file because when I read data from file with variables of class so, I will lost more time. My question is that how I can cast derived class bikeType
to vehicleType
.
#pragma once
#ifndef vehicleType_H
#define vehicleType_H
#include<string>
#include"recordType.h"
using namespace std;
class vehicleType
{
private:
int ID;
string name;
string model;
double price;
string color;
float enginePower;
int speed;
recordType r1;
public:
friend ostream& operator<<(ostream&, const vehicleType&);
friend istream& operator>>(istream&, vehicleType&);
vehicleType();
vehicleType(int id,string nm, string ml, double pr, string cl, float
enP, int spd);
void setID(int id);
int getID();
void recordVehicle();
void setName(string);
string getName();
void setModel(string);
string getModel();
void setPrice(double);
double getPrice();
void setColor(string);
string getColor();
void setEnginePower(float);
float getEnginePower();
void setSpeed(int);
int getSpeed();
void print();
};
#endif
#pragma once
#ifndef bikeType_H
#define bikeType_H
#include"vehicleType.h"
#include<iostream>
using namespace std;
class bikeType :public vehicleType
{
private:
int wheels;
public:
bikeType();
bool operator<=(int);
bool operator>(bikeType&);
bool operator==(int);
bikeType(int wls, int id, string nm, string ml, double pr, string
cl,float enP, int spd);
void setData(int id, string nm, string ml, double pr, string cl,
float enP, int spd);
void setWheels(int wls);
int getWheels();
friend istream& operator>>(istream&, bikeType&);
friend ostream& operator<<(ostream&, const bikeType&);
void print();
};
#endif
I have defined all functions of base and derived classes but only stream insertion and stream extraction operators could not defined.
Upvotes: 1
Views: 567
Reputation: 716
Add a virtual function to base class and define it in derived classes.
class vehicleType
{
// ...
virtual ostream& output(ostream& os) = 0;
};
class bikeType :public vehicleType
{
// ...
ostream& output(ostream& os) override
{
return os << "I am a bike!";
}
};
Define output operator like this:
ostream& operator<<(ostream& os, const vehicleType& v)
{
return v.ouput(os);
}
Upvotes: 1
Reputation: 238281
- Can I define separately stream insertion and extraction operators of base and derived classes?
Yes. As you have done.
- If we derive class from base class then how can I cast and overload stream insertion and extraction operator?
You can use a static cast to a reference to base if you would like to call the extraction operator of the base.
Upvotes: 0