Jump to content

jonatas

Veterans
  • Posts

    3
  • Joined

  • Last visited

Reputation

0 Neutral

Recent Profile Visitors

811 profile views
  1. Looks like you can do that using boost, but I'm not sure how to do it and it still doesn't seem safe. To be honest, even in languages like Java that you can do this through the use of generics, you'll still get either a compiler warning, a runtime exception if you access something wrong or both. Basically, you might be able to do what you want, but it is bad code and, even though manually casting each time is annoying, it is the safest option.
  2. I don't know much about C++, but you can do a few things. The first thing is to use the keyword virtual on the foo method of the Parent class. This way it'll call the method's implementation of the instatiated object and not the the one of the parent class. By using virtual you'll get something like that: Parent *p1 = new Parent; Parent *c1 = new Child_1; Parent *c2 = new Child_2; p1->foo(); // prints "I'm a parent" c1->foo(); // prints "I'm a Child 1" c2->foo(); // prints "I'm a Child 2" // Remember to delete the pointers you created afterwards Of course that this way you still can't call the bar method of the Child_1 class, you'll probably get a compiler error. To do so, you need to explicitly cast the pointer to a Child_1 type. Something like that. Parent *p1 = new Parent; Parent *c1 = new Child_1; p1->bar(); // compiler error c1->bar(); // compiler error Child_1 *cp1 = (Child_1*) p1; Child_1 *cc1 = (Child_1*) c1; cp1->bar(); // compiles, but the behavior is undefined cc1->bar(); // prints "This is defnitely a Child 1" I've never used anything to check the type of an object in C++. In java there's the instanceof operator, but, as pointed here, if you want to cast something in a polymorphic situation it's a sign that there's probably somthing wrong with the way you designed your code. Since it seems like you're only learning how things work, the same link shows that you can use a dynamic_cast, the documentation says that it returns the casted value or a null pointer, this way you can use somehing like that: Parent *p1 = new Child_1; Child_1 *c1; if(c1 = dynamic_cast<Child_1*>(p1)) { c1->bar(); } I hope I could help you and that I did not say anything wrong. By the way, I preferJava because it's easier and I also like the documentation better, but C and C++ teaches you how to be more conscious regarding the resources and how to manage memory better. If you can learn C++ well you'll easily dominate things like Java, C#, Python, etc.
×
×
  • Create New...