vendredi 23 octobre 2020

Accessing private struct of a class using auto

I discovered that next weird code compiles and runs (on VS 2019):

#include <iostream>

class Test
{
    private:
    struct Priv
    {
        int a;
    };
    
    public:
    static Priv WeirdFunc() {return {42};}; 
};

int main()
{
    auto val = Test::WeirdFunc();
    std::cout << val.a;
}

Output is 42, no problems here.

The issue I see is that auto keyword allows us to access private structure "Priv". If I try to replace auto with Test::Priv I get compile error, as expected. From the articles on the internet I found out that you can have to use auto for lambdas, but this case was never mentioned.

Also, if I try to output "Test::WeirdFunc().a" it also works

So my questions are:

  • Is it expected behaviour for auto to let us access private structures/classes?
  • Is it allowed to declare public function that returns private structure?
  • Is it expected behaviour that we can access private structures/classes if it's return value of function (e.g. "Test::WeirdFunc().a")?

All of that is obviously terrible code style, but I'm curious about whether it's valid c++ code or not

Aucun commentaire:

Enregistrer un commentaire