Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Same class as a member inside a class in C++?

Sorry I ill formed the question earlier. The piece of code is something like:

class Bar
{
    public:
        // some stuff

    private:
        struct Foo
        {
            std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo;
            // some other basic variables here
        };

        Foo foo;
};

I got the basic idea about subFoo. But I am wondering that a single instance of Bar will contain only a single instance of Foo that is foo member variable? So a single instance/object of Bar will not be able to map multiple Foo inside the subFoo?

It feels like I am missing something here, can anyone break it down for me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are more misunderstandings about nested class definitions than there are actual benefits. In your code it really does not matter much and we can change it to:

struct Foo {
    std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo;
    // some other basic variables here
};

class Bar
{
        Foo foo;
};

Foo is now defined in a different scope and it is no longer private to Bar. Otherwise it makes no difference for the present code.

I am wondering that a single instance of Bar will contain only a single instance of Foo that is foo member variable?

Yes.

So a single instance/object of Bar will not be able to map multiple Foo inside the subFoo?

subFoo is a map holding unique pointers to Foos. Bar::foo is not managed by a unique pointer, hence placing them in subFoo is not possible without running into a double free error. std::unique_ptr can be used with a custom deleter, but thats not the case here. Hence you cannot store a unique pointer to Bar::foo in any Foo::subFoo. You can however, store unique pointers to other Foos in Foo::subFoo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading