0

I'm working on the C++ project where I have to overload operands in a generic class (template class).

So, I have a sample class like this:

template <class T>
class SomeClass {
private:
    T variable;
public:
    explicit SomeClass(T variable) : variable(variable) {}

    SomeClass operator + (SomeClass const &someClass) {
        return SomeClass<T>(this->variable + someClass.variable);
    }
};

And main method like this:

int main() {
    SomeClass<int>* obj1 = new SomeClass<int>(5);
    SomeClass<int>* obj2 = new SomeClass<int>(7);

    SomeClass<int>* result = obj1 + obj2;

    return 0;
}

If I hover the "+" sign, I'm seeing this error message:

Invalid operands to binary expression ('SomeClass<int> *' and 'SomeClass<int> *')

What is the cause of this error?

If I don't use pointers, everything works fine. (when I write smth like this):

int main() {
    SomeClass<int> obj1(5);
    SomeClass<int> obj2(7);

    SomeClass<int> result = obj1 + obj2;

    return 0;
}

Note: I have to use pointers in my app, so the last code snippet isn't viable for me.

Serhii Chernikov
  • 353
  • 2
  • 11
  • 3
    `*obj1 + *obj2`, but you should really prefer another instructor. – Evg Nov 08 '22 at 17:09
  • Thanks a million guys!! Yep, it's a really weird task. – Serhii Chernikov Nov 08 '22 at 17:11
  • I remember a C course I took taught by an electrical engineer. I'd already swallowed up a couple years of computer science, so I was puzzled by the lack of coverage of pointers in the class. "Don't need 'em," he explained when asked. Thought he was crazy back then. He wasn't. Just limited the options a bit too much by leaving them out. At the end of the day, it's the differing points of view that really allow you to learn. – user4581301 Nov 08 '22 at 17:19
  • @user4581301 although that is true, it's pretty weird to completely miss out on learning such an important feature. I bet electrical engineers writing microcontroller code can get away with using pointers a lot less, because the program is relatively simple. (Regardless, the exercise in this question is a dumb way to teach pointers) – user253751 Nov 08 '22 at 17:23
  • The difference between a pointer and the object is points to is like the difference between your house's address and your house. Your house's address is a short snippet of data that gives people information as to where your house is located. Your house's address is not itself your house. – Eljay Nov 08 '22 at 17:29
  • @Eljay C and C++ are very different languages. C++ having references is only one of the many differences between the languages. – DevSolar Nov 09 '22 at 20:23

0 Answers0