TIP: Click on subject to list as thread! ANSI
echo: os2prog
to: All
from: Micah Yoder
date: 1994-08-10 18:06:04
subject: C++ Object Conversions

Hi!

I want to convert a program written in Borland Pascal to C++ so I can
port it to OS/2.  This might not be specific to OS/2, but if I'm to
port it I need to figure this problem out....

Ok, here's the sample program I'm testing:

// C++ Test
// Micah Yoder

#include 

class BaseClass {
    protected:
    int x;
    public:
    BaseClass(int a) {x = a;};
    virtual int operation(void) {return x*x;};
    ~BaseClass() { };
};

class ChildClass : public BaseClass {
    private:
    int y;
    public:
    ChildClass(int a, int b) :BaseClass(a) {x = a; y = b;};
    virtual int operation(void) {return x*y;};
    ~ChildClass() { };
};

main()
{
    BaseClass *test, *temp;
    ChildClass *MyVar, *MySecondVar;

    test = new BaseClass(5);
    MyVar = new ChildClass(2, 3);

    printf("BaseClass operation returns %d", test->operation());
    printf("ChildClass operation returns %d", MyVar->operation());

    temp = MyVar;

    printf("Temp operation returns %d", temp->operation());

// This line is the problem:
    MySecondVar = (ChildClass)temp;

    printf("MySecondVar operation returns %d",
MySecondVar->operation());

    delete test;
    delete MyVar;
}

My problem is converting temp, a variable of type BaseClass which
obviously contains a ChildClass, back to ChildClass (MySecondVar).
I can do this in Borland Pascal by using a statement like:

  MySecondVar := {at}temp^;

and it works great.  You can use a statement like that to assign any pointer
to any other pointer, regardless of their types.  C++ gives me an error
and I can't seem to get around it.

The real program that I'm trying to convert uses a byte in the base
object to define exactly which decendent type it is, so I can be
100% sure I'm converting to the correct type.  I know this probably
isn't in the spirit of C++, but I do know what I'm doing (:-)) and
I can't think of a way around it....

Any pointers would be appriciated.
  
___
 X ATP/OS2 1.42 X void clinton() {lie(); jog(); lie(); eat(big_mac); jog();}

--- Maximus/2 2.01wb

* Origin: OS/2 Shareware BBS, Fairfax, VA: 703-385-4325 (1:109/347)
SEEN-BY: 12/2442 54/54 620/243 624/50 632/348 640/820 690/660 711/409 413 430
SEEN-BY: 711/807 808 809 934 712/353 623 713/888 800/1
@PATH: 109/347 2 1 3615/50 229/2 12/2442 711/409 54/54 711/808 809 934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.