Home > Backend Development > C++ > Is Private Class Member Type Deduction with `auto` Valid in C ?

Is Private Class Member Type Deduction with `auto` Valid in C ?

Patricia Arquette
Release: 2024-12-16 01:48:14
Original
999 people have browsed it

Is Private Class Member Type Deduction with `auto` Valid in C  ?

Auto on Private Types

Using auto to declare a variable can be confusing when dealing with private class members. In this example, the code compiles successfully:

class Foo {
    struct Bar { int i; };
public:
    Bar Baz() { return Bar(); }
};

int main() {
    Foo f;
    auto b = f.Baz();
    std::cout << b.i;
}
Copy after login

Is this code valid? If so, why?

The code is indeed valid. auto follows the same rules as template type deduction. The reason both auto b = f.Baz(); and fun(f.Baz()); compile is because the type of Foo::Bar is usable, even though its name is private.

Why is the type usable if its name is private?

The inaccessibility of private types extends only to their names. The types themselves can still be used, making it possible to return them to client code and pass them to template functions.

The above is the detailed content of Is Private Class Member Type Deduction with `auto` Valid in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template