Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a class member variable to a function as default variable?

Tags:

c++

I want to pass class variable a in a class function as default parameter. I can do this by using #define but I want to do it by using the class member. Is there any way to do this?

#include <iostream>
    
    class Test
    {
    private:
        int a=5;
    public:
        Test(){}
        void function(int value=a){ //i want to use class variable a here.
            std::cout<<value<<std::endl;
        }
        ~Test(){}
    };
    
    int main()
    {
        Test var1;
        var1.function();
        return 0;
    }

This program shows error: invalid use of non-static data member

like image 774
Md. Akash Avatar asked Apr 20 '26 05:04

Md. Akash


1 Answers

One simple solution is to use overloading instead:

class Test
{
private:
    int a=5;
public:
    void function(int value){
        std::cout<<value<<std::endl;
    }

    // Overload for no arguments, use a as "default" argument
    void function(){
        function(a);  // Call using the member variable
    }
};
like image 139
Some programmer dude Avatar answered Apr 21 '26 19:04

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!