I have following Classes:
class Vehicle
{
public:
Vehicle(int id);
virtual int getID() const;
virtual void setCustom(Customer* custom);
virtual Customer *getCustom() const;
virtual void printOnce() const = 0;
protected:
int id_;
Customer* custom_;
};
Vehicle::Vehicle(int id)
: id_{id}, custom_{nullptr}
{
}
class Car : public Vehicle
{
public:
Car(int id, int seats, string color);
virtual void printOnce() const override;
private:
int seats_;
int color_;
};
Car::Car(int id, int seats, string color)
: Vehicle(id), seats_{seats}, color_{color}
{
}
class Customer
{
public:
Customer(string customerName, int age, int driverlicenceType);
string getCustomerName() const;
private:
string customerName_;
int age_;
int driverlicenceType_;
};
Customer::Customer(string customerName, int age, int driverlicenceType)
: customerName_{customerName}, age_{age}, driverlicenceType_{driverlicenceType}
{
}
string Customer::getCustomerName() const
{
return customerName_;
}
and the following Method:
Vehicle *CarRental::findByName(string name)
{
auto cmp =[name](Vehicle* v){
if(v->getCustom() != nullptr) {
return name == v->getCustom()->getCustomerName();
}
};
//find Vehicle in vector <Vehicle*> vehicles_;
return (*find_if(vehicles_.begin(), vehicles_.end(), cmp));
}
Now I'm trying to get the Vehicle*, cast it to Car*, and test if the Customer is nullptr.
Code:
Vehicle* veh = findByName(name);
Car* c = dynamic_cast<Car*>(veh);
if(c->getCustom() == nullptr) {
//do anything
}
But somehow it isn't nullptr. If I try to get the name or age:
cout << "Customer: " << c->getCustom() << endl;
it shows me only Customer: (like an empty string). I think if it were nullptr this should not work and give me an error but I don't know why.