3.0k views
3 votes
Consider the class Polar, which has two double member variables r and theta. Which of these is a correct copy constructor for Polar?

a) Polar(const Polar& other) : r(other.r), theta(other.theta) {}
b) Polar(Polar& p) { r = p.r; theta = p.theta; }
c) Polar(double r, double theta) : r(r), theta(theta) {}
d) Polar(double r) : theta(0), r(r) {}

1 Answer

5 votes

Final answer:

a) Polar(const Polar& other) : r(other.r), theta(other.theta) {}

The correct copy constructor for the class Polar which initializes r and theta member variables is 'Polar(const Polar& other) : r(other.r), theta(other.theta) {}'. This uses an initializer list to copy the value of these variables from the other object.

Step-by-step explanation:

The question pertains to identifying the correct copy constructor for a class Polar that has two member variables r and theta. A copy constructor in C++ is a special constructor that initializes a new object as a copy of an existing object. The correct answer is:

a) Polar(const Polar& other) : r(other.r), theta(other.theta) {}

This defines a copy constructor that takes a constant reference to another Polar object and uses an initializer list to copy the values of r and theta from the passed object to the newly constructed object. The other options provided are either not copy constructors or incorrectly formed for a copy constructor.

User Antti
by
8.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.