Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning member class in C++

Tags:

c++

types

In the following example:

class A
{
public:
    class B
    {
        ...
    }
    B Method(B argument);
}

A::B A::Method(B argument);

Why exactly is the scope required for return type, while not for argument type?

like image 570
szpanczyk Avatar asked Jan 11 '17 01:01

szpanczyk


People also ask

How do I return a class object?

Syntax: object = return object_name; Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type 'Example'(i.e., class name) whose value is stored in E3.

What does return {} mean in C++?

The return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was called.

Can a class have a return?

Yes, a class can have a method that returns an instance of itself.

What is returning by reference?

When a function returns a reference, it returns an implicit pointer to its return value. This way, a function can be used on the left side of an assignment statement.


1 Answers

According to [basic.lookup.qual]/3,

In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope of the member’s class or namespace.

The return type comes before the qualified-id being declared (that is, A::Method) whereas the parameter type comes after it, so the parameter type's name is automatically looked up in the scope of A, while the return type's name is not. We can avoid the extra qualification using a trailing return type.

auto A::Method(B argument) -> B;
like image 66
Brian Bi Avatar answered Oct 01 '22 06:10

Brian Bi