145k views
1 vote
Given the following code for a car class with methods start and brake, which of the following is legal? car *car;car car2;group of answer choices

a. car2->start(); ();
b. car->brake();
c. car2->brake();

User Speerian
by
8.5k points

1 Answer

1 vote

None of the given options is legal. To make it legal, initialize the `car` pointer with memory allocation using `new`, or use an object directly. Example: `car* car = new car(); car->start(); car->brake();` Option D: None of the above is the answer.

None of the provided options is legal because there is no memory allocation for the `car` pointer, and attempting to access methods through an uninitialized pointer or object can lead to undefined behavior. To make it legal, you should allocate memory for the `car` pointer using `new` or use an object directly. Here's an example:

car* car = new car();

car->start(); // Legal

car->brake(); // Legal

// or

car car2;

car2.start(); // Legal

car2.brake(); // Legal

Make sure to free the memory allocated with `new` using `delete` when it's no longer needed to avoid memory leaks.

So the answer is option D. None of the above.

The complete question is:

given the following code for a car class with methods start and brake, which of the following is legal? car *car;car car2;group of answer choices

a. car2->start(); ();

b. car->brake();

c. car2->brake();

d. None of the above

User Kyrie
by
7.9k points