March 11, 2012

Psycho_Path Psycho_Path
Lab Rat
19 posts

Problem using overridden methods

Page  
1

So I created a class and sub-classes that override the parent’s class looking something like this

  1. MyClass()
  2. {
  3. }
  4.  
  5. void MyClass::doSomething()
  6. {
  7.     cout << "MyClass::doSomething()";
  8. }

  1. MyCClass1() (inherits from MyClass in the header file)
  2. {
  3. }
  4.  
  5. void MyCClass1::doSomething()
  6. {
  7.     cout << "MyCClass1::doSomething()";
  8. }

  1. MyCClass2() (inherits from MyClass in the header file)
  2. {
  3. }
  4.  
  5. void MyCClass2::doSomething()
  6. {
  7.     cout << "MyCClass2::doSomething()";
  8. }

  1. void main(etc...)
  2. {
  3.     vector<MyClass> storage;
  4.     MyCClass1 mcc1();
  5.     MyCClass2 mcc2();
  6.     storage.push_back(mcc1);
  7.     storage.push_back(mcc2);
  8.     for (int i = 0; i < storage.size(); i++)
  9.     {
  10.         storage[i].doSomething();
  11.     }
  12. }

How do i get the vector’s call to doSomething() to use the child classes doSomething() methods instead of the parent classes method? I’ve tried using virtual classes, but then the vector can’t call the method as it’s virtual for any MyClass objects.

Thanks in advance.

21 replies

March 11, 2012

leon.anavi leon.anavi
Mad Scientist
1062 posts

You can cast instances of MyCClass1 and MyCClass2 to MyCClass and then to call the method doSomething:

  1.  
  2. // type cast derived-to-base
  3. MyClass* pBase = dynamic_cast<MyClass*>(&storage[i]);    
  4. pBase->doSomething();

 Signature 

http://anavi.org/

March 11, 2012

Psycho_Path Psycho_Path
Lab Rat
19 posts

It actually occurred to me a bit after making this post that that’s what I’d probably have to do. Is there a simple way of knowing which of MyCClass1 or MyCClass2 each of the objects in storage is without having some reference variable in MyClass?

March 11, 2012

mlong mlong
Mad Scientist
1517 posts

Try to dynamic_cast to each of the known types. If it casts, it’s that type. If you get a 0 back, then it’s not.

 Signature 

Senior Software Engineer
AccuWeather Enterprise Solutions
/* My views and opinions do not necessarily reflect those of my employer.  Void where prohibited. */

March 11, 2012

Psycho_Path Psycho_Path
Lab Rat
19 posts

What do you mean get back a 0? if I do

  1. MyCClass1* pBase = dynamic_cast<MyCClass1*>(&storage[i]);

then pBase will = 0?

March 11, 2012

leon.anavi leon.anavi
Mad Scientist
1062 posts

Psycho_Path wrote:
What do you mean get back a 0? if I do

  1. MyCClass1* pBase = dynamic_cast<MyCClass1*>(&storage[i]);

then pBase will = 0?

Depends :) What tools do you use to build your source code?

In general dynamic_cast returns a null pointer to indicate a failure. If dynamic_cast of references is not possible a bad_cast exception is thrown.

But if you are using Microsoft Visual C++ 2005 or newer then 0 will be returned on failure and no exception will be thrown. Please check Microsoft documentation for details : http://msdn.microsoft.com/en-us/library/cby9kycs(v=vs.80).aspx

 Signature 

http://anavi.org/

March 11, 2012

Wilk Wilk
Ant Farmer
120 posts

Hello
Try this out

  1.     void main(etc...)
  2.     {
  3.         vector<MyClass *> storage;
  4.         MyCClass1 *mcc1 = new MyCClass1();
  5.         MyCClass2 *mcc2 = new MyCClass2();
  6.         storage.push_back(mcc1);
  7.         storage.push_back(mcc2);
  8.         for (int i = 0; i < storage.size(); i++)
  9.         {
  10.             storage[i] ->doSomething();
  11.         }
  12.     }

March 11, 2012

whpp whpp
Lab Rat
4 posts

Wilk’s solution works, though be careful!

Any added functionality in your derived classes (MyCClass1 and MyCClass2) cannot be called this way and will have to be dynamically casted to their respective derived class pointers. Say you have a doMore() function in MyCClass1, but not in MyClass:

  1. storage[0]->doMore();

The above will not work, whereas the below will:

  1. dynamic_cast<MyCClass1 *>(storage[0])->doMore();

Edit: Don’t forget to use operator delete() after those operator new()s

March 11, 2012

broadpeak broadpeak
Hobby Entomologist
360 posts

Casting is unnecessary. Use the polymorphism. In the Base class the doSomething() should be virtual. All other will be solved by the C++ compiler.

March 11, 2012

Wilk Wilk
Ant Farmer
120 posts

whpp wrote:

Any added functionality in your derived classes (MyCClass1 and MyCClass2) cannot be called this way and will have to be dynamically casted to their respective derived class pointers.

If you need such functionality, you’d better use a container of objects of derived classes (MyCClass1 and MyCClass2), not of base class (MyClass) or of pointers to objects of base class. If each of derived classes has additional functionality (doMore()) then you should add a virtual or a pure virtual method in your base class, as broadpeak said above.

March 11, 2012

Zlatomir Zlatomir
Robot Herder
327 posts

Virtual or not virtual, cast or no cast – this code wont work polymorphic

  1.     vector<MyClass> storage;
  2.     MyCClass1 mcc1();
  3.     MyCClass2 mcc2();
  4.     storage.push_back(mcc1);  //you slice your objects here storage has a copy of MyClass "part" of your objects
  5.     storage.push_back(mcc2);
  6.     for (int i = 0; i < storage.size(); i++)
  7.     {
  8.         storage[i].doSomething();
  9.     }

For polymorphic call you need pointers or references (and since vector can’t hold references you must use pointers):
  1.     vector<MyClass*> storage;
  2.     MyCClass1 mcc1();
  3.     MyCClass2 mcc2();
  4.     storage.push_back(&mcc1);
  5.     storage.push_back(&mcc2);
  6.     for (int i = 0; i < storage.size(); i++)
  7.     {
  8.         storage[i]->doSomething(); //add virtual in the MyClass declaration
  9.     }

//just remember that the pointers stored in storage will be invalid when the objects get out of scope
or if you allocate dynamically you must delete the allocated memory before vector gets out of scope or before you remove the pointers from vector.

March 11, 2012

whpp whpp
Lab Rat
4 posts

@Zlatomir: Yes, that’s basically Wilk’s implementation, only using the address of-operator instead of all pointers.

Wilk wrote:
whpp wrote:
Any added functionality in your derived classes (MyCClass1 and MyCClass2) cannot be called this way and will have to be dynamically casted to their respective derived class pointers.
If you need such functionality, you’d better use a container of objects of derived classes (MyCClass1 and MyCClass2), not of base class (MyClass) or of pointers to objects of base class. If each of derived classes has additional functionality (doMore()) then you should add a virtual or a pure virtual method in your base class, as broadpeak said above.

Of course. That’s a valid option, but that would change the semantics of the example at hand.

March 11, 2012

Zlatomir Zlatomir
Robot Herder
327 posts

whpp wrote:
@Zlatomir: Yes, that’s basically Wilk’s implementation, only using the address of-operator instead of all pointers…

You miss the point of my post, i only posted the code because i missed *Wilk*’s code

So the point was that the objects are sliced at push_back and you can do whatever you want with the objects (or their addresses) in the vector<MyClass> the objects are only MyClass objects – not MyClass1 so there is no way you can do any of MyClass1 specific functionality.

whpp wrote:
…Of course. That’s a valid option, but that would change the semantics of the example at hand.

You can’t solve this issue without changing the semantics, because it’s a misuse of polymorphism, since as i said earlier you don’t have any derived objects into the vector.

March 12, 2012

Psycho_Path Psycho_Path
Lab Rat
19 posts

I think casting seems to make the most sense here as in my actual code, the vector is filled in a different function than the function that iterates through the vector to call the function that both sub-classes have. I don’t really see any other way of accessing the other methods in each of the sub-classes the other way either. For the record, I’m using Qt to develop this code.

March 12, 2012

Zlatomir Zlatomir
Robot Herder
327 posts

As i said i my first post casting will fail (for vector<MyClass>) there is no way to use MyClass1 (or any other derived functionality) because that part of your objects is lost. (this cast: MyClass1* pBase = dynamic_cast<MyClass1*>(&storage[i]); will fail for storage of type vector<MyClass>)

To use the overridden functions from that vector you need to use pointers into the vector, than the overridden functionality will work correctly and also the casting (of-course to the correct pointer type).

//also since MyClass is designed as base class don’t forget the virtual destructor (for the case you call delete on a MyClass* that has the address of a dynamically allocated MyClass1 object)

March 12, 2012

Psycho_Path Psycho_Path
Lab Rat
19 posts

Heh, since my last post I’ve come to realize what you’ve said to be very much true, however, in my actual code, as the objects created are being made in a function that ends before the call to the function that doSomething() gets called in is ran, the objects get deleted and the pointers are pointing to null memory. Is there any way to cast without using pointers that will work? Or should I just come up with a completely different structure for my code to run that doesn’t involve this polymorphism?

Edit: Just realized what you pointed out in your previous post about the functionality being lost as the vector allocates memory of size MyClass and not either of the MyCClass classes. In any case, is there an easy solution here? Or do I just have to use 2 seperate vectors of type MyCClass1 and MyCClass2?

Page  
1

  ‹‹ snprintf usage?      [SOLVED] capture the output of a class ››

You must log in to post a reply. Not a member yet? Register here!