0

I think the title of question is little bit confusing, so I'll explain that.

Let's see this very simple code.

#include <iostream>

class C {
public:
    int val;

    C(){
        val = 2;
    }

    void changeVal(int i){
        val = i;
    }

};

void printout(int val){
    std::cout << "int val : " << val << std::endl;
}

void printout(C c){
    std::cout << "class val : " << c.val << std::endl;
}

int main()
{
    C c;
    printout(1);
    printout(c);    

    //printout(C());    // ok, I can understand it.
    //printout(C().changeVal(0)); /// ?????
    return 0;
}

As you can see, function 'printout' is for printing out the input argument. My question is, when I use the int value(default datatype), then I just put in the function real number '1', however, when I use my class instance('class C'), then I have to declare my class instance before the function.

So, is there any way to make this kind of non-default datatype for function argument in 1-line?

The actual situation is, I have to use the 4x4 matrix as argument for some function. For this reason, I have to make some matrix, and initialize(make zero) that, and use it. But if I can do this same job with just 1 line, my source code will be more clear than now.

That's my question. I hope you could understand my question. Thank you.

5
  • I've removed the C tag. The use of class and <iostream> implies that this question is about C++ only Commented Aug 22, 2013 at 6:36
  • do you mean can you do printout(C()) Commented Aug 22, 2013 at 6:38
  • Btw not sure what you mean by "Default datatype", "built in language datatype/primitive type" would be better Commented Aug 22, 2013 at 6:40
  • @simonc Thank you for your guide. I'm not familiar this system Commented Aug 22, 2013 at 6:47
  • @KarthikT Oh, that kinds of representation is much better. Thank you. Commented Aug 22, 2013 at 6:51

1 Answer 1

2

You can pass a temporary:

printout(C());

Note that, since you don't need a copy of the C parameter, it would make more sense to pass it by const reference:

void printout(const C& c) { ... }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. Then I want to ask one more question. Can I use my member function for initialization with similar way?
I added 'changeVal' function. I want to initialize my member variable 'val' as 0, then I'll use 'changeVal' function for that. Can I do this job in 1 line for function argument?
@CIMPLE if you want to initialize val to 0, you don't need to call changeVal. You can write the default constructor like this: C() : val(0) {} or even C() : val() {}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.