I have to classes car and vehicle I am trying to use parametrized constructor to set values for the Car object members but it gives errors
#include <iostream>
#include <string>
class vehicle {
int wheels ;
double price ;
std::string color ;
public:
vehicle(int , double , std::string ) ;
void initialize (int , double , std::string ) ;
~vehicle (void) ;
};
class car : public vehicle {
int load ;
double weight ;
public:
car (int , double , int wheels , double price , std::string color ) ;
void initialize (int , double , std::string , int , double ) ;
~car (void) ;
};
car::car(int load , double weight , int wheels , double price , std::string color ): vehicle (wheels ,price , color )
{
this->load = load ;
this->weight = weight ;
}
vehicle::vehicle(int w,double p,std::string c)
{
initialize(w,p,c);
}
void vehicle::initialize(int w,double p,std::string c)
{
wheels = w;
price = p;
color = c;
}
it gives an error in the car Constructor line
You have to explicitly call your base constructor and with constructor initializer list you can greatly simplify your code:
#include <string>
class vehicle {
int wheels ;
double price ;
std::string color ;
public:
vehicle(int wheels, double price, std::string color) :
wheels(wheels), price(price), color(color){}
};
class car : public vehicle {
int load ;
double weight ;
public:
car (int load, double weight , int wheels, double price, std::string color ) :
vehicle(wheels, price, color), load(load), weight(weight){}
};
int main() {
car c(4, 1500, 4, 36000, "white");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.