C++: How to return abstract class in a method of this abstract class

Viewed 314

I have an abstract class and it has two derived classes. I'm trying to overload operator+ in the base class so I could do derivedClass=derivedClass+differentDerivedClass like this:

class iMatrix{
iMatrix operator+(const iMatrix& obj)
}

class UsualMatrix : public iMatrix

class SparseMatrix : public iMatrix 

Inside of main, I want to do

SparseMatrix a, b;
UsualMatrix c=a+b;

I have copy constructors and everything that may be helpful. Now if I create the function like

iMatrix operator+(const iMatrix& obj)

Compiler (LLVM in Xcode) says "Return type 'iMatrix' is an abstract class", but theoretically everything else should work properly. I've read manuals and other StackOverflow threads, so I've tried this:

iMatrix& operator+(const iMatrix& obj)

Whereas function on its own does "add obj to this" and returns *this. The problem is when I do c=a+b, a becomes equal to c, but it should not be changed.

a=
1 1 
1 1 
b=
1 1 
1 1 
a+b=c; 
c=
2 2 
2 2 
b=
1 1 
1 1 
a=
2 2 
2 2 

What should I do? Addition and multiplying must be implemented inside of base class, and I have no idea how to fix this error. Any advice would be appreciated, thanks.

2 Answers
Related