So i have this code:
vehicle *v1=&c;
std::cout<<"Car: "<<endl;
v1->input(cin);
Vehicle is a base class and Car is the derived one. They both share a virtual function input
. The problem is that whenever i call this method, the program can only fill the base part. Here is the code for the input.
For the base class:
istream& vehicle::input(istream& is) {
char buffer[100];
is.getline(buffer,100);
set_type(buffer);
is.getline(buffer,100);
set_brand(buffer);
is.clear();
return is;
}
And for car, derived class:
istream& car::input(istream& is) {
vehicle::input(is);
char buffer[100];
is.getline(buffer,100);
set_alim(buffer);
is.clear();
return is;
}
I also tried deleting the call vehicle::input(is);
and the program doesn't do anything. Supposedly it cannot recognize the virtual method. How do I fix this?
As required:
class vehicle {
friend ostream& operator<<(ostream&, const vehicle&);
friend istream& operator>>(istream&, vehicle&);
protected:
char* type;
char* brand;
public:
//constructors
void set_type(const char* t) {
delete [] type;
type=new char(strlen(t)+1);
strcpy(type,t);
}
void set_brand(const char* t) {
delete [] brand;
brand=new char(strlen(t)+1);
strcpy(brand,t);
}
virtual istream& input(istream&);
};
class car:public vehicle {
friend ostream& operator<<(ostream&, const car&);
friend istream& operator>>(istream&, car&);
private:
char* alim;
public:
//constructors
void set_alim(const char* a) {
delete [] alim;
alim=new char(strlen(a)+1);
strcpy(alim,a);
}
virtual istream& input(istream&);
};
EDIT: I found the bug, the problem was not using is.ignore()
even though if you create a new project and build the code exactly as i did, it works just fine