C++ Syntax Question:
Download Job Interview Questions and Answers PDF
What are the basics of local (auto) objects?
Answer:
C++ extends the variable declaration syntax from built-in types (e.g., int
i;) to objects of user-defined types. The syntax is the same: TypeName VariableName.
For example, if the header file “Car.hpp” defines a user-defined type called Car,
objects (variables) of class (type) Car can be created:
#include "Car.hpp" // Define class Car
void f()
{
Car a; // 1: Create an object
a.startEngine(); // 2: Call a member function
a.tuneRadioTo("AM", 770); // 3: Call another member function
} // 4. Destroy the object
int main()
{
f();
}
When control flows over the line labeled 1: Create an object, the runtime
system creates a local (auto) object of class Car. The object is called a and can
be accessed from the point where it is created to the } labeled 4: Destroy the
object.
When control flows over the line labeled 2: Call a member function, the
startEngine() member function (a.k.a. method) is called for object a. The
compiler knows that a is of class Car so there is no need to indicate that the
proper startEngine() member function is the one from the Car class. For
example, there could be other classes that also have a startEngine() member
function (Airplane, LawnMower, and so on), but the compiler will never get
confused and call a member function from the wrong class.
i;) to objects of user-defined types. The syntax is the same: TypeName VariableName.
For example, if the header file “Car.hpp” defines a user-defined type called Car,
objects (variables) of class (type) Car can be created:
#include "Car.hpp" // Define class Car
void f()
{
Car a; // 1: Create an object
a.startEngine(); // 2: Call a member function
a.tuneRadioTo("AM", 770); // 3: Call another member function
} // 4. Destroy the object
int main()
{
f();
}
When control flows over the line labeled 1: Create an object, the runtime
system creates a local (auto) object of class Car. The object is called a and can
be accessed from the point where it is created to the } labeled 4: Destroy the
object.
When control flows over the line labeled 2: Call a member function, the
startEngine() member function (a.k.a. method) is called for object a. The
compiler knows that a is of class Car so there is no need to indicate that the
proper startEngine() member function is the one from the Car class. For
example, there could be other classes that also have a startEngine() member
function (Airplane, LawnMower, and so on), but the compiler will never get
confused and call a member function from the wrong class.
Download Basic C++ Syntax Interview Questions And Answers
PDF
Previous Question | Next Question |
Explain what are the Sizes and ranges of the Basic C++ data types? | What is the most common mistake on C++ and OO projects? |