Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. Problem using overridden methods
QtWS25 Last Chance

Problem using overridden methods

Scheduled Pinned Locked Moved C++ Gurus
24 Posts 9 Posters 12.7k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Z Offline
    Z Offline
    Zlatomir
    wrote on 11 Mar 2012, 16:46 last edited by
    #11

    Virtual or not virtual, cast or no cast - this code wont work polymorphic
    @ vector<MyClass> storage;
    MyCClass1 mcc1();
    MyCClass2 mcc2();
    storage.push_back(mcc1); //you slice your objects here storage has a copy of MyClass "part" of your objects
    storage.push_back(mcc2);
    for (int i = 0; i < storage.size(); i++)
    {
    storage[i].doSomething();
    }@
    For polymorphic call you need pointers or references (and since vector can't hold references you must use pointers):
    @
    vector<MyClass*> storage;
    MyCClass1 mcc1();
    MyCClass2 mcc2();
    storage.push_back(&mcc1);
    storage.push_back(&mcc2);
    for (int i = 0; i < storage.size(); i++)
    {
    storage[i]->doSomething(); //add virtual in the MyClass declaration
    }
    @
    //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.

    https://forum.qt.io/category/41/romanian

    1 Reply Last reply
    1
    • W Offline
      W Offline
      whpp
      wrote on 11 Mar 2012, 17:35 last edited by
      #12

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

      [quote author="Wilk" date="1331481313"][quote author="whpp" date="1331476875"]
      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.[/quote]
      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.
      [/quote]

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

      1 Reply Last reply
      0
      • Z Offline
        Z Offline
        Zlatomir
        wrote on 11 Mar 2012, 18:08 last edited by
        #13

        [quote author="whpp" date="1331487349"]@Zlatomir: Yes, that's basically Wilk's implementation, only using the address of-operator instead of all pointers...[/quote]
        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.

        [quote author="whpp" date="1331487349"]...Of course. That's a valid option, but that would change the semantics of the example at hand.
        [/quote]
        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.

        https://forum.qt.io/category/41/romanian

        1 Reply Last reply
        0
        • P Offline
          P Offline
          Psycho_Path
          wrote on 12 Mar 2012, 15:23 last edited by
          #14

          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.

          1 Reply Last reply
          0
          • Z Offline
            Z Offline
            Zlatomir
            wrote on 12 Mar 2012, 15:50 last edited by
            #15

            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)

            https://forum.qt.io/category/41/romanian

            1 Reply Last reply
            0
            • P Offline
              P Offline
              Psycho_Path
              wrote on 12 Mar 2012, 16:15 last edited by
              #16

              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?

              1 Reply Last reply
              0
              • W Offline
                W Offline
                Wilk
                wrote on 12 Mar 2012, 16:34 last edited by
                #17

                [quote author="Psycho_Path" date="1331568900"]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?[/quote]
                I gave you solution in my first post:
                @ void main(etc...)
                {
                vector<MyClass *> storage;
                MyCClass1 *mcc1 = new MyCClass1();
                MyCClass2 *mcc2 = new MyCClass2();
                storage.push_back(mcc1);
                storage.push_back(mcc2);
                for (int i = 0; i < storage.size(); i++)
                {
                storage[i] ->doSomething();
                }
                }
                @

                As you can see, you create objects using operator new(), so the pointers won't become invalid after exiting the function, where thery were created. From other hand you have to make destructor of base class (MyClass) virtual and explicity delete every object, when you've done:
                @
                foreach (MyClass *element,
                storage) {
                delete element;
                }
                @

                That's the classical way of creating a polymorphic behaviour. For more information try to read Bjarne Stroustrup C++ Programming Language, The (3rd Edition).

                1 Reply Last reply
                0
                • P Offline
                  P Offline
                  Psycho_Path
                  wrote on 12 Mar 2012, 17:43 last edited by
                  #18

                  Thanks for your help and for re-posting what you'd already taken the time to post that I'd overlooked. Much appreciated.

                  1 Reply Last reply
                  0
                  • B Offline
                    B Offline
                    broadpeak
                    wrote on 12 Mar 2012, 19:34 last edited by
                    #19

                    Yes, point at Wilk . Polymorphism (with pointers) can help.
                    @
                    #include <iostream>
                    #include <vector>

                    using namespace std;

                    class MyClass
                    {
                    public:
                    virtual void doSomething() const
                    {
                    cout << "MyClass::doSomething" << endl;
                    }
                    };

                    class MyCClass1: public MyClass
                    {
                    public:
                    void doSomething() const
                    {
                    cout << "MyClass1::doSomething" << endl;
                    }
                    };

                    class MyCClass2: public MyClass
                    {
                    public:
                    void doSomething() const
                    {
                    cout << "MyClass2::doSomething" << endl;
                    }
                    };

                    /*
                    void writeall(vector<MyClass*>& s)
                    {

                    for (int i = 0; i < s.size() ; i++)
                    {
                        s[i]->doSomething();
                    }
                    

                    }
                    */

                    int main()
                    {
                    vector<MyClass*> storage;
                    MyCClass1* mcc1 = new MyCClass1();
                    MyCClass2* mcc2 = new MyCClass2();
                    storage.push_back(mcc1);
                    storage.push_back(mcc2);

                    //writeall(storage);
                    
                    for (int i = 0; i < storage.size() ; i++)
                    {
                        storage[i]->doSomething();
                    }
                    
                    return 0;
                    

                    }
                    @

                    1 Reply Last reply
                    0
                    • Z Offline
                      Z Offline
                      Zlatomir
                      wrote on 13 Mar 2012, 12:16 last edited by
                      #20

                      broadpeak you forgot the virtual destructor for MyClass and also you forgot to delete the dynamic allocated memory.

                      https://forum.qt.io/category/41/romanian

                      1 Reply Last reply
                      0
                      • B Offline
                        B Offline
                        broadpeak
                        wrote on 13 Mar 2012, 16:27 last edited by
                        #21

                        [quote author="Zlatomir" date="1331641008"]broadpeak you forgot the virtual destructor for MyClass and also you forgot to delete the dynamic allocated memory.[/quote]

                        I have forgotten nothing :)
                        But in this very simple example I would have liked to avoid any complications: I focused only polymorphically behavior. Of course, you are right, in a bigger project we have to use virtual desctructor.

                        1 Reply Last reply
                        0
                        • Z Offline
                          Z Offline
                          Zlatomir
                          wrote on 13 Mar 2012, 17:38 last edited by
                          #22

                          The polymorphic parts were posted before, so i assumed you wanted to give a complete example... and the things i said you forgot are pretty important parts of the example.

                          Anyway i "vote" for you to edit the post and add the missing parts, i don't think that 4 lines of code would complicate the example.

                          https://forum.qt.io/category/41/romanian

                          1 Reply Last reply
                          0
                          • osirisgothraO Offline
                            osirisgothraO Offline
                            osirisgothra
                            wrote on 22 Nov 2024, 21:11 last edited by
                            #23

                            I do really like being able to do this:

                            class MyObj : public SomeObj<-right click here....

                            go to refactor->insert virtual functions of base classes

                            which opens a wonderful window that displays EVERY child class of that object with a checkbox by each function. You can just check off each signature you want to override and be done with it in one go!

                            I'm truly glad you r/offmychess t finally, but please don't go too far, because you r/beyondvoxels and that implies that u r/donewithlife. Oh well time to git back to the lab, because azure sea here, I have a lot of work to do...

                            Pl45m4P 1 Reply Last reply 25 Nov 2024, 13:14
                            0
                            • osirisgothraO osirisgothra
                              22 Nov 2024, 21:11

                              I do really like being able to do this:

                              class MyObj : public SomeObj<-right click here....

                              go to refactor->insert virtual functions of base classes

                              which opens a wonderful window that displays EVERY child class of that object with a checkbox by each function. You can just check off each signature you want to override and be done with it in one go!

                              Pl45m4P Offline
                              Pl45m4P Offline
                              Pl45m4
                              wrote on 25 Nov 2024, 13:14 last edited by Pl45m4
                              #24

                              @osirisgothra said in Problem using overridden methods:

                              I do really like being able to do this:

                              which opens a wonderful window that

                              You could write a QtCreator extension/plugin and try to find out how to get your hand on the data you need.

                              displays EVERY child class of that object with a checkbox by each function. You can just check off each signature you want to override

                              Probably via the Code Model / Symbols.

                              If you wanna try it, start a new topic.
                              People who have more experience with such things than I do may be able to help you then.


                              If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                              ~E. W. Dijkstra

                              1 Reply Last reply
                              0

                              • Login

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • Users
                              • Groups
                              • Search
                              • Get Qt Extensions
                              • Unsolved