ozma
ozma

Reputation: 1803

Return instance by value from a method stack compilation

Can you explain why this won't compile:

(this is the error:

../Man.cpp:33:9: error: conversion from ‘Man (*)()’ to non-scalar type ‘Man’ requested)

Code:

Man goo(){
  Man m();
  return m;
}

but this does:

Man goo(){
    return Man();
}

Upvotes: 2

Views: 95

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61607

Man m();

This means "somewhere else in the program, I will define a function named m that takes no arguments and returns a Man". Yes, even when you write it inside another function.

Man m;

This means "m is a variable of type Man". Since Man is a class type, the default constructor will be called and no parentheses are necessary.

Upvotes: 5

Carl Norum
Carl Norum

Reputation: 225032

You don't want those parentheses in your first example:

Man goo(){
  Man m;
  return m;
}

Upvotes: 3

user1192525
user1192525

Reputation: 677

You don't need () in the first case. The default constructor is called implicitly.

Man goo(){
    Man m;
    return m; 
}

In the second case you are calling the constructor.

Upvotes: 2

Related Questions