0
0
C++programming~10 mins

Why constructors are needed in C++ - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a constructor for the class.

C++
class Car {
public:
    [1]() {
        speed = 0;
    }
private:
    int speed;
};
Drag options to blanks, or click blank then click option'
Acar
BCar
Cvoid Car
Dint Car
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using lowercase 'car' instead of 'Car'.
Adding a return type like 'void' or 'int' to the constructor.
2fill in blank
medium

Complete the constructor to initialize the member variable 'speed' with the given value.

C++
class Car {
public:
    Car(int s) {
        [1] = s;
    }
private:
    int speed;
};
Drag options to blanks, or click blank then click option'
Aspeed
Bs
CCar::speed
Dthis->speed
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Assigning to the parameter s instead of the member variable.
Using just 'speed' without this-> which can cause confusion.
3fill in blank
hard

Fix the error in the constructor declaration to properly initialize 'speed'.

C++
class Car {
public:
    Car(int s) : [1](s) {}
private:
    int speed;
};
Drag options to blanks, or click blank then click option'
Aspeed
Bs
Cthis->speed
DCar::speed
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the parameter name 's' instead of the member variable 'speed' in the initializer list.
Using 'this->speed' which is not allowed in initializer lists.
4fill in blank
hard

Fill both blanks to create a constructor that sets 'speed' and 'color' with given values.

C++
class Car {
public:
    Car(int s, std::string c) : [1](s), [2](c) {}
private:
    int speed;
    std::string color;
};
Drag options to blanks, or click blank then click option'
Aspeed
Bs
Ccolor
Dc
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using parameter names instead of member variable names in the initializer list.
Mixing up the order of initialization.
5fill in blank
hard

Fill all three blanks to create a constructor that initializes 'speed', 'color', and 'model'.

C++
class Car {
public:
    Car(int s, std::string c, std::string m) : [1](s), [2](c), [3](m) {}
private:
    int speed;
    std::string color;
    std::string model;
};
Drag options to blanks, or click blank then click option'
Aspeed
Bcolor
Cmodel
Dm
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using parameter names instead of member variable names in the initializer list.
Forgetting to initialize one of the member variables.