Inheritance: assign base class to derived class
I have defined a class Matrix, which represents a generic m x n matrix. I derive from this class a specialized Matrix3D class, which represents a 3 x 3 matrix. I run into problems when I try to use the functionality of the base class with my derived class. Specifically my base class contains a member that computes the transpose of the matrix and returns it as a new matrix:
Code:
class Matrix
{
public:
Matrix(int m, int n);
Matrix transpose();
};
Now when I try to apply this member to my derived class, i.e.
Code:
class Matrix3D: public Matrix
{
public:
Matrix3D(): Matrix(3, 3);
};
Matrix3D M;
Matrix3D N = M.transpose();
This results in a compiler error "error: conversion from 'Matrix' to non-scalar type 'Matrix3D' requested". Now this may be explained by a derived class not knowing exactly what the base class looks like as the private members of the base class are hidden from it and it can therefore not get a base type assigned.
The solution to my problem would be as simple as reimplementing the transpose() member in the Matrix3D class, but this seems to defeat the purpose of inheriting from this class. So how would I solve this problem in a 'correct' manner?