简体   繁体   中英

accessing data member through composition

I have a struct obj in my base class. I don't know how to access the data members of the struct through Derv1 class (Derived from the base class). I tried making both Base and Derv1 a friend of struct - it still tells me ' data member is private' (its private in Base only).

example :

struct A{
    public :
        int total;
        //some stuff
};
class MyClass{ // [Base] class
    private:
      A var1;
};

class Derv1{
    private:
        //some stuff
        public void display_var1(Derv1 x){
            return x.var1.total;
        }  // trying to return the value of A.total
};

I hope this makes sense so that you can help me out .. Thank You kindly,

i think you must extend your Derv1 class into the Base class:

class Derv1: public MyClass{

to inherit the members of the base class

First, you have to make sure that Derv derives from MyClass .

class Derv1 : public MyClass { ... };

and then, you will need to figure out the best way to display the variable.

My suggestion:

  1. Create a virtual member function in the base class.
  2. Override the function in the derived class.
  3. Make sure to call the base class implementation in the derived class implementatin.

class MyClass { // [Base] class

    public:

        virtual void display() const
        {
           // Display var1 anyway you wish to.
        }

    private:
      A var1;
};

class Derv1 : public MyClass {

    public:

        virtual void display() const
        {
           // Call the base class implementation first
           MyClass::display():

           // Display anything else that corresponds to this class
        }

    private:
        //some stuff
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM