5

If I have the following c++ code:

class foo{
public:
    explicit foo(int i){};
};
void f(const foo &o){
}

And then I call

f(foo(1));

Is foo(1) constructor call or function-style cast?

5
  • Can't you only call constructors that way when declaring variables? Commented Nov 27, 2011 at 23:30
  • @Inerdial: not sure I understand you. Can you elaborate a bit? Thanks. Commented Nov 27, 2011 at 23:33
  • 2
    @Inerdial: No, you can call constructors like that too. Commented Nov 27, 2011 at 23:38
  • @QiangLi: I was asking if it's at all possible to call constructors without new as an expression, not as a variable declaration statement. (That said it's more of a vague guess which is why it's a comment not an answer.) Commented Nov 27, 2011 at 23:40
  • @Inerdial: it tends to get a bit vague when java/pythonists start guessing about C++ language features. Please post helpful comments when you're pretty certain you're contributing. Commented Nov 27, 2011 at 23:53

3 Answers 3

4

They are the same thing.

Sign up to request clarification or add additional context in comments.

5 Comments

you mean I can consider them as either case?
LOL at <!---------> (I had to see how you managed that) +1
@sehe: sorry about my English. What did you imply?
@QiangLi : that was at @OliCarlesworth :)
(Edit the answer to see what it means... answers need to be padded to a certain length, so Oli used a HTML comment to do it. This is going in my bag of tricks)
4

It's a function-style cast that results in a constructor call, so both.

1 Comment

I thought only one is suffice. Then making a temporary copy to feed into the function is the next step thing. my question is only worrying about the code foo(1) part.
4

5.2.3 Explicit type conversion (functional notation)

1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). ...

Your code creates a temporary, using the constructor you have with the argument's value 1, and binds it to a const reference. The temporary's lifetime ends at the end of the statement where it was created.

Comments

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.