-1

Add two structure data of same type and store it finalInstance

#include <iostream>

using namespace std;

typedef struct counter {
    int Stx_cnt;
    int End_cnt;
    int data;
}
counter_t;

class Base {
    public:
        Base() {}
    counter_t firstInstance;
    counter_t secondInstance;

};

int main() {
    Base obj1;
    obj1.firstInstance = {
        1,
        2,
        10
    };
    obj1.secondInstance = {
        3,
        4,
        20
    };
    counter_t finalInstance = obj1.firstInstance + obj1.secondInstance;
    return 0;
}

I have some data in firstInstance and secondInstance and want to add then and store in finalInstance without accessing through their members and my finalInstance should have {4,6,30};

enter image description here

  • where is your code? – foragerDev Jul 10 '21 at 08:12
  • Please don't use pictures of text, just copy'n'paste it into your question. – Ulrich Eckhardt Jul 10 '21 at 08:22
  • In any case, you can overload `operator+` for your type easily. The basics of this should be in any C++ book and examples are all over the internet. – Ulrich Eckhardt Jul 10 '21 at 08:24
  • Are you simply trying to allow the use of the plus operation on the struct without modifying the struct itselt? This would be rather simple: just implement the operation outside on namespace scope. If you're trying to the thing your question asks about though, i.e. implementing the addition without using the member names (`Stx_cnt`, `End_cnt` and `data`) you'll probably need to make some assumptions about the struct layout. – fabian Jul 10 '21 at 08:26

1 Answers1

0

C++ will not automatically add a plus operator for custom data types. This you need to do by yourself.

So, there is no way around. You must access the structure members.

But it is simple. Please add this piece of code before your main function:

counter operator +(const counter& left, const counter& right) {
    counter result{};
    result.Stx_cnt = left.Stx_cnt + right.Stx_cnt;
    result.End_cnt = left.End_cnt + right.End_cnt;
    result.data = left.data + right.data;
    return result;
}
A M
  • 14,694
  • 5
  • 19
  • 44