#Help with C++

6 messages · Page 1 of 1 (latest)

viscid plank
#

hey guys i hope that you are doing well , i have a question here its about C++ i have a question if we have a derived class, can we use a constructor to initialize inherited attributes in listed constructors method like in the code bellow :

#include <string>
#include <iostream>
using namespace std;

class Vehicle {
protected:
string type;
string brand;
int speed = 90;

public:

void getVehicleInfo() {
    cout << "Vehicle Informations:\n";
    cout << "Type: " << type << "\n";
    cout << "Speed: " << speed << " km/h\n";
}

};

class Car : public Vehicle {
public:
Car() : type = ("Voiture") , speed (204) {
cout << "Car set successfully ! ";
}

void setSpeed (int vitesse){
if (vitesse < 500 || vitesse > 0)
    speed = vitesse;
}

};

int main() {
Car VW;
//VW.setSpeed(90);
VW.getVehicleInfo();

return 0 ;
}
it gives an error in line 22.

fringe sluice
#

An initializer list for protected members isn't possible in the way you're attempting

#

You'll need to make a constructor for the parent class to forward those initialization values to, a la

class Vehicle {
protected:
    std::string type;
    int speed;

public:
    Vehicle(const std::string& type, const int& speed): type(type), speed(speed) {}
};

class Car : public Vehicle {
public:
    Car() : Vehicle("Voiture", 204) {
        std::cout << "Car set successfully !\n";
    }
};
viscid plank
woven helm
#

there is a syntax error in your constructor for the Car class. When initializing base class members in the member initializer list of a derived class constructor, you should use the base class constructor to initialize those members. for more info DM!

earnest idol
#

!warn @woven helm You've already been told to stop asking people to DM you