www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript

c++ - Type cast to subclass

↑ ↓ ← Iliya Peregoudov <iliyap mail.ru> writes:
Sample code:

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

class Matrix {
protected:
    int v[3][3];
public:
    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 {
private:
    int det;
public:
    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()
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
objects?

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
↑ ↓ → "Walter" <walter digitalmars.com> writes:
That's a bug. I'll fix it in the next patch.
Sep 23 2002