C++ Class Question

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
Ion Dune
Posts: 453
Joined: Mon Nov 12, 2007 8:29 pm
Location: California, USA
Contact:

C++ Class Question

Post by Ion Dune »

I have one class, Class1, and a derived class Class2. If I make a Class1 pointer, and then attribute it to Class2, will this create problems when tying to access members of Class1? Here's pseudo code:

Code: Select all

class Class1
{
public:
int a;
}

Class1* pointer;

class Class2 : public Class1
{
}
and then somewhere in main/function

Code: Select all

pointer=&(some instance of Class 2 here);

pointer->a+=100;
Is this legal?

Thanks for your time.
Kriolyth
Posts: 26
Joined: Wed Mar 26, 2008 6:59 pm
Location: Moscow, Russia

Post by Kriolyth »

Yes, it's legal, safe and no problems should arise. Moreover, if I'm not mistaken, even static_cast is not needed (you'd be advised to use it when casting to derived classes).
The cake is a lie.
Ion Dune
Posts: 453
Joined: Mon Nov 12, 2007 8:29 pm
Location: California, USA
Contact:

Post by Ion Dune »

Thanks for your quick reply. I managed to find that my problem was actually that the pointer pointed to where the temporary Class2 was created for my array of Class2's, and not to the actuall class. Thanks!
MasterGod
Posts: 2061
Joined: Fri May 25, 2007 8:06 pm
Location: Israel
Contact:

Post by MasterGod »

But this means that the Class1 pointer, even that it points to a data of Class2 it will have the interface of Class1 so if for example Class2 has methodZ and Class1 has methodA your pointer would be able to call only methodA of Class1 or better saying that your pointer will Not be able to call any Class2 member (be it a method or an attribute)
Image
Dev State: Abandoned (For now..)
Requirements Analysis Doc: ~87%
UML: ~0.5%
Kriolyth
Posts: 26
Joined: Wed Mar 26, 2008 6:59 pm
Location: Moscow, Russia

Post by Kriolyth »

MasterGod wrote:But this means that the Class1 pointer, even that it points to a data of Class2 it will have the interface of Class1 so if for example Class2 has methodZ and Class1 has methodA your pointer would be able to call only methodA of Class1 or better saying that your pointer will Not be able to call any Class2 member (be it a method or an attribute)
...unless it is explicitly cast to Class2* ;)

Just in case - pointer to array of classes has to be deleted with operator "delete[]", as opposed to operator "delete" for classes.

Code: Select all

Class2* inst = new Class2();
Class2* arr = new Class2[10];
delete inst;
delete[] arr;
A simple yet common pitfall :)
The cake is a lie.
Post Reply