High School

Given the following code for a car class with methods start and brake, which of the following is legal?

```cpp
car *car;
car car2;
```

Choose the correct option:

1. `car2->start();`
2. `car->brake();`
3. `car2->brake();`

Answer :

Final answer:

The correct method call syntax in C++ depends on whether you have an object or a pointer to an object. car2 should use the dot operator because it's an object, while a pointer like car would use the arrow operator.

Explanation:

The question involves C++ programming, specifically the syntax for calling methods on objects and pointers. When calling a method on an object of a class in C++, you use the dot operator (.), and when calling a method on a pointer to an object, you use the arrow operator (->).

Based on the code provided:

  • car *car; is a declaration of a pointer to a car object, not an actual car object.
  • car car2; is an actual car object.

Therefore:

  1. car2->start(); - This is incorrect because car2 is not a pointer, so you should use the dot operator, not the arrow operator.
  2. () is incomplete and therefore not a legal operation.
  3. car2->brake(); - Again, this is incorrect due to using the arrow operator with an actual object; it should be car2.brake().
  4. The call car->brake(); would be legal assuming car had been properly initialized to point to a car object.