Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Nested classes driving me crazy

Tags:

c++

class

nested

i am trying to compile this very simple piece of code

class myList
{
public:
    std::vector<std::string> vec;
    class Items
    {
    public:
        void Add(std::string str)
        {
            myList::vec.push_back(str);
        };
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

what can i do to make this work without creating more objects that needed or overcomplicating stuff...

like image 448
SMeyers Avatar asked Oct 25 '08 21:10

SMeyers


People also ask

Are nested classes a code smell?

According to that yes, it's a code smell. However, whether you want to follow the advice given there is your decision. It has advantages and disadvantages and weighting them against each other and coming to a conclusion is opinion-based and something we don't do here.

Is it good practice to use nested classes?

Nested Class can be used whenever you want to create more than once instance of the class or whenever you want to make that type more available. Nested Class increases the encapsulations as well as it will lead to more readable and maintainable code.

What are the advantages disadvantages of nested classes?

Which among the following is the correct advantage/disadvantage of nested classes? Explanation: The use of nested classes makes the code more streamed towards a single concept. This allows to group the most similar and related classes together and makes it even more efficient and readable.

What is the point of nested classes?

As mentioned in the section Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code.


1 Answers

Add a couple of constructors and a pointer to the parent class.

#include <string>
#include <vector>
class myList
{
public:
    std::vector<std::string> vec;
    myList(): items(this) {} // Added
    class Items
    {
    public:
        Items(myList *ml): self(ml) {}  // Added
        void Add(std::string str)
        {
                self->vec.push_back(str); // Changed
        };
        myList *self; //Added
    }items;
};

int main()
{
    myList newList;
    newList.items.Add("A");
}

You need the myList() constructor, so it registers instances of itself with the instance of the inner class member variable. Then you need the Items constructor to store the pointer to the outer myList class instance. Finally in the Add method, you need to reference vec in the stored myList instance.

As Catskul points out, the Item constructor mustn't actually do anything with the myList pointer it receives. I'd also like to say that though this answer is closer to the original intent, steveth45's answer is closer to what you would want to do in a real program.

like image 58
richq Avatar answered Oct 30 '22 04:10

richq