210k views
5 votes
Write a person constructor that uses an initialization list for age and sex fields

A) Person(int age, char sex) : age(age), sex(sex) {}
B) Person(int age, char sex) { this->age = age; this->sex = sex; }
C) Person : age(0), sex(' ') {}
D) Person(age, sex) : age(age), sex(sex) {}

User Mier
by
8.1k points

1 Answer

0 votes

Final answer:

Option A provides the correct constructor with an initialization list for the 'age' and 'sex' fields. It's the most efficient way to initialize class member variables with parameters that have the same name.

Step-by-step explanation:

The student's question pertains to the initialization of class members in C++. Specifically, they are asking how to write a Person constructor that uses an initialization list for the age and sex fields. Let's evaluate the provided options:

  • A) Person(int age, char sex) : age(age), sex(sex) {} - This is the correct way to use an initialization list. The members are initialized before the body of the constructor, which is more efficient, especially for constructor parameters that have a matching name with class member variables.
  • B) Person(int age, char sex) { this->age = age; this->sex = sex; } - This approach assigns the values inside the constructor's body instead of using an initialization list. It is not incorrect, but it's not what the question is asking for.
  • C) Person : age(0), sex(' ') {} - This syntax is incorrect; there is no constructor defined here with parameters.
  • D) Person(age, sex) : age(age), sex(sex) {} - This is missing the data types for the parameters, which makes the syntax incorrect.

The correct answer is A, which provides a properly formatted constructor with an initialization list.

User Kartik Domadiya
by
8.2k points