www.digitalmars.com         C & C++   DMDScript  

c++ - Type cast to subclass

reply Iliya Peregoudov <iliyap mail.ru> writes:
Sample code:

/* subcast.cpp */
#include <memory.h>
#include <iostream.h>

class Matrix {
    int v[3][3];
    Matrix() { cerr << "Matrix::ctor()" << endl; };
    Matrix(const Matrix &m) {
       cerr << "Matrix::ctor(const Matrix &)" << endl;
       memcpy(v, m.v, sizeof(v));

class SquareMatrix: public Matrix {
    int det;
    SquareMatrix(): Matrix() {
       cerr << "SquareMatrix::ctor()" << endl;
       det = 0;
    SquareMatrix(const SquareMatrix &m): Matrix(m) {
       cerr << "SquareMatrix::ctor(const SquareMatrix &)" << endl;
       det = m.det;

int main()
    Matrix m1;
    SquareMatrix m2((SquareMatrix)m1);

    return 0;

This compiles ok and runs ok giving on stderr:

Matrix::ctor(const Matrix &)
SquareMatrix::ctor(const SquareMatrix &)

This mean that only two objects constructed: m1 of type Matrix (first
output line) and m2 of type SquareMatrix (second and third output
lines).  So the question:  How the compiler converts object of class
Matrix to objects of its subclass SquareMatrix without creating any

This sample code gives compile-time error about unability to convert
from Matrix to SquareMatrix while compiled by g++ and KAI C++.
Sep 23 2002
parent "Walter" <walter digitalmars.com> writes:
That's a bug. I'll fix it in the next patch.
Sep 23 2002