Home > database >  How to access and modify value of a struct which is a public member of a class (c )
How to access and modify value of a struct which is a public member of a class (c )

Time:08-28

i would like to know how can i access and modify the struct's attributes in the constructor of my class. Thanks

template <class K, class V>
    class AVLTree
    {
        public:
            struct Node
            {
                Node *parent;
                Node *right;
                Node *left;
                int height;
            };
    // CONSTRUCTOR
            AVLTree(){
                Node::parent = NULL; // Access struct attributes here
            }

CodePudding user response:

structs, by themselves, are not entities of any kind, that have any kind of an attribute, or anything.

A struct, by itself, is just a definition for an object that claims to be that struct.

An object, of the struct's type, will have the attributes and methods that are a part of the struct's definition.

So, for example, if your AVLTree template has a member

Node n;

then the AVLTree constructor can set this member:

n.parent=nullptr;

However, that's not even the best way to do this. You will discover that the best way to avoid bugs in C code is to make it logically impossible for them to happen. Right now it is possible to forget to initialize Node's members, and cause bugs because of that.

So, to fix that, have Node itself provide default values for its members, with its own constructor.

But it's not even necessary to do that, with modern C , just define the default values for the attributes, or class members:

            struct Node
            {
                Node *parent=nullptr;
                Node *right=nullptr;
                Node *left=nullptr;
                int height=0;
            };

            Node n;

Now, nothing needs to be done in AVLTree's constructor, and you automatically avoid all bugs due to uninitialized class members.

  • Related