Home > Backend Development > C++ > body text

Why Can't a Member Variable Be Used as a Default Argument in a C Member Function?

DDD
Release: 2024-11-14 17:00:02
Original
955 people have browsed it

Why Can't a Member Variable Be Used as a Default Argument in a C   Member Function?

Using a Member Variable as Default Argument in C

In C , it's possible to specify a default argument for a member function using a member variable. However, attempting to use a member function as the default argument may result in a compiler error, as seen in the example below.

class Object {
protected:
   Point initPos;
   Point currPos;

   void MoveTo(double speed, Point position = initPos);
};

void Object::MoveTo(double speed, Point position) {
   currPos = postion;
}
Copy after login

This code will encounter the following compilation error:

error: invalid use of non-static data member 'Object::initPos'
Copy after login

Reason for the Error

Default argument expressions in member functions are restricted to using elements within the class or at global scope. Here, the compiler cannot determine the value of the initPos member variable when the function is called, leading to the error.

Solution

To resolve this issue, use function overloading with the following approach:

// Single-argument overload that defaults to initPos
void Object::MoveTo(double speed) {
   MoveTo(speed, initPos);
}

// Two-argument overload that takes the explicit position
void Object::MoveTo(double speed, Point position) {
   // Implementation here
}
Copy after login

Advantages

This technique allows for optional argument handling in member functions while maintaining implementation in a single method. It follows the DRY (Don't Repeat Yourself) principle by avoiding code duplication while providing a convenient way to specify default values.

The above is the detailed content of Why Can't a Member Variable Be Used as a Default Argument in a C Member Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template