Home >Backend Development >C++ >Why Can't I Use Member Variables as Default Arguments in C Member Functions?

Why Can't I Use Member Variables as Default Arguments in C Member Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 10:23:02678browse

Why Can't I Use Member Variables as Default Arguments in C   Member Functions?

Utilizing Member Variables as Default Arguments in C

In object-oriented programming, member variables often serve as default values for method arguments. However, when attempting to set a member variable as a default argument, you may encounter errors like "invalid use of non-static data member."

Problem Description

You aim to make an argument of a member function optional, using a member variable as the default value when no argument is provided. However, your code produces the error message "invalid use of non-static data member." You suspect a problem with your code but are unsure of the solution.

Code Snippet

Below is the provided code to illustrate the issue:

class Object {
public:
    void MoveTo(double speed, Point position);
protected:
    Point initPos; 
    Point currPos;
};

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

Solution

Default argument expressions for member functions can only rely on elements within the class or global scope. Additionally, the default argument must be defined in the method's declaration (header file).

To address this, employ two overloads of the MoveTo method: one with a single argument and one with two arguments. The method with the single argument calls the method with the two arguments, passing the intended default value.

void Object::MoveTo(double speed) {
    MoveTo(speed, initPos);
}

void Object::MoveTo(double speed, Point position) {
    // Implementation
}

By invoking MoveTo(double) and subsequently calling MoveTo(double, Point), this technique allows you to implement MoveTo only once, following the DRY principle (Don't Repeat Yourself).

The above is the detailed content of Why Can't I Use Member Variables as Default Arguments in C Member Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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