car.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Create a class for a car

#include <iostream>
#include <string>

class Car
{
private:
    std::string color;
    std::string type;
    float weight;
    // '*' is a pointer to a float

public:
    int nb_wheels;
    float *wheels; // one float per wheel

public:
    // Constructor
    Car(std::string the_type, std::string color, float weight, int nb_wheels = 4)
    {
        type = the_type;
        this->color = color;
        this->weight = weight;
        this->nb_wheels = nb_wheels;
        this->wheels = new float[nb_wheels];
    }
    Car()
    {
        this->color = "Red";
        this->type = "Sedan";
        this->weight = 2000; // lb
    }

    // Destructor (~)
    ~Car()
    {
        delete [] wheels;
    }

    // create a function
    void drive()
    {
        std::cout << "Driving" << std::endl;
    }

    void brake()
    {
        std::cout << "Braking" << std::endl;
    }

    void internal_lights()
    {
        std::cout << "Internal lights on" << std::endl;
    }

    float getWeight() { return weight; }
    std::string getType() { return type; }
    std::string getColor() { return color; }
    void setWeight(float weight) { this->weight = weight; }
    void setType(std::string type) { this->type = type; }
    void setColor(std::string color) { this->color = color; }
};

int main()
{
    std::cout << "Hello, World!" << std::endl;

    Car toyota;
    Car nissan("Nissan", "blue", 1200.);

    std::cout << "Toyota color: " << toyota.getColor() << std::endl;
    std::cout << "Nissan type: " << nissan.getType() << std::endl;
    std::cout << "Nissan color: " << nissan.getColor() << std::endl;
    std::cout << "Nissan weight: " << nissan.getWeight() << std::endl;
    nissan.setWeight(5000);
    std::cout
        << "Nissan weight: " << nissan.getWeight() << std::endl;
    // std::cout << "Toyota weight: " << toyota.weight << std::endl;

    toyota.drive();
    // toyota.brake();
    return 0;
}
Back to week02