Home >Backend Development >C++ >Why Does 'auto' Work with Private Types While Explicit Declaration Fails?
When working with private types within a class, you might encounter a curious situation: while attempting to explicitly declare a variable using the type name results in an error, using 'auto' to infer the type seems to work seamlessly.
class Foo { struct Bar { int i; }; public: Bar Baz() { return Bar(); } };
In the given code, Foo contains a private nested type Bar. Executing the following line throws an error:
Foo::Bar b = f.Baz(); // error
Unexpectedly, employing 'auto' resolves the issue:
auto b = f.Baz(); // ok
Why is this permitted?
Both 'auto' type deduction and template type inference share a similar underlying mechanism. In this instance, it resembles how 'template' functions can work with private types:
template <typename T> void fun(T t) {} int main() { Foo f; fun(f.Baz()); // ok }
Unveiling the Accessibility
The ability to pass objects of private types to template functions or use 'auto' to infer their type stems from the fact that the type itself remains accessible, even though its name is hidden. The compiler, through type deduction, unravels the structure of the object, enabling its utilization.
Therefore, while the name of a private type is inaccessible, its type information is still available, allowing manipulation through mechanisms like 'auto' or template deduction.
The above is the detailed content of Why Does 'auto' Work with Private Types While Explicit Declaration Fails?. For more information, please follow other related articles on the PHP Chinese website!