Reputation: 309
English is not my first language. I hope I will not make lot of mistakes. I'll try my best to be as clear as possible!
I have a base class
class engine
{
private :
std::string name;
double weight;
public:
engine();
~engine();
std::string getName() const;
int getWeight() const
};
std::string engine::getName() const{
return this->name;
}
int engine::getWeight() const{
return this->weight;
}
and derived class
class diesel : public engine
{
private:
std::string name;
double weight;
public:
diesel();
~diesel();
};
diesel::diesel(){
this->name = Diesel;
this->weight = 500.00;
}
In my main.cpp
int main()
{
diesel diesel_engine;
const engine &e = diesel_engine;
std::cout<<e.getWeight()<<e.getName()<<std::endl;
return 0;
}
1- I must construct a diesel class named diesel_engine.
2- pass diesel_engine's value to a new engine by reference??
When I call const engine &e = diesel_engine;
, diesel_engine's value(name and weight) should be copied to the new engine e.
So 'e' should have weight of 500.00 and the name "Diesel".
I don't get how can I use polymorphism to do that.
Thank you for reading this question!
Upvotes: 0
Views: 36
Reputation: 1894
Lets start with the class declarations
class Engine
{
private:
float weight_;
std::string name_;
public:
Engine(float weight, std::string name) : weight_(weight), name_(name){};
std::string GetName() const { return name_;}
};
class Diesel : public Engine
{
public:
Diesel(float weight, std::string name) : Engine(weight, name){}
};
So what we have here is an Engine
class which is our base class
and then we define our Diesel class
, Diesel
inherits from Engine
and passes the arguments to its base class.
Now to use this:
Diesel disel_engine(0.0, "diesel engine");
const Engine& eng = disel_engine;
cout << eng.GetName();
The call to eng.GetName()
prints the correct engine name
Upvotes: 1