I am trying to find a way to create a generic "car" class, with children that overload the parent's methods. Subsequently, I would like to have a user class that has as a member any class in the "car" family. Is there a way to achieve the desired functionality? Thank you!
The pseudocode below shows what my intial attempt was, but the compiler obviously complains that User wants a Car object, not a Toyota.
class Car
{
public:
Car();
void method1();
};
class Toyota : public Car
{
public:
Toyota();
void method1();
};
class Lada : public Car
{
public:
Lada();
void method1();
};
class User
{
public:
User();
Car car;
};
int main()
{
User user;
Toyota toyota;
user.car = toyota;
}
CodePudding user response:
Derived to base conversion is possbile only with a pointer or a reference to the base class(Car
in our example). This means that you need to make the data member car
to be of type Car&
or Car*
as shown below:
class User
{
public:
//-----------vvvv---------------------->added this parameter
User(Car& pCar):car(pCar){}
//----------v-------------------------->make car a Car&
Car &car; //now we have a reference to the base class Car
};
int main()
{
Toyota toyota;
//-------------vvvvvv-------->pass as argument
User user(toyota);
}
Additionally, the member functinon method
should be made virtial if you want to be able to use dynamica binding.
You might also refer to can dynamic binding happen without using pointer and using regular object in c .
CodePudding user response:
i think you should use virtual functions inside car and a reference pointer on assigning class toyota to car, the code i written below is working good.
#include <iostream>
using std::cout;
class Car
{
public:
Car(){cout << "A car";};
virtual void method1(){cout << "from car";};
};
class Toyota : public Car
{
public:
Toyota(){cout << "A toyota";};
void method1() {cout << "from toyota";};
};
class Lada : public Car
{
public:
Lada(){cout << "A Lada";};
void method1() {cout << "from lada";};
};
class User
{
public:
User(){cout << "A user";};
Car *car;
};
int main()
{
User *user = new User();
Toyota toyota;
user->car = &toyota;
/***
if you dont need pointers then
User user;
Toyota toyota;
user.car = &toyota;
/**
}