polymorphism, is their a better way to do this

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bums735 bums735
    New Member
    • Dec 2011
    • 3

    polymorphism, is their a better way to do this

    hello everyone, im a bit new to c++, im missing a concept of polymorphism. my problem is i cant figure out another way to override a method.
    Code:
     
    #include <iostream>
    class Base {
    public:
       Base();
       ~Base();
    public:
       virtual void OutPut() {std::cout << "Base" << std::endl;}
    };
    
    class Derived : Base {
    public:
       Derived();
       ~Derived();
    public:
       virtual void OutPut() {std::cout << "Derived" << std::endl;}
    };
    
    int main(){
    Base* baseptr = new Derived;
    baseptr->OutPut();
    }
    now this is just a very quick example that i wrote up but the thing is im not going to have much control of overriding it like that by saying
    Code:
    Base* baseptr = new Derived;
    in the function thats going to be in a library that i will be importing into my main project, so the question i guess is, is their another way to override a method without going to the root of where it gets called? i have a feeling im missing something simple.

    thank you for any help you give me
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The whole point of polymorphism is that you can have an interface defined on a generic object type (Base::Output in your example) and when you call that interface on the generic object it actually performs the action for the specific object in question, i.e. calls Derived::Output .

    The important point is that within the hierarchy the method Output should perform semantically the same function for all objects, that is your shouldn't implement a Derrived2 where Output actually requests information from the user.

    That is polymorphism.

    However that does not stop you calling the function directly from the object itself i.e. calling Derived::Output directly without conversion to a base pointer. That isn't polymorphism (unless of course Derived has further sub-classes) but is just using the functionality of the class Derived. That doesn't change the fact that Output is an inherently polymorphic function.

    Does that help? It is not entirely clear what you query actually is.

    Comment

    • bums735 bums735
      New Member
      • Dec 2011
      • 3

      #3
      I believe so yes, thank you for your response, i appreciate it. ill be back if i need more help :D

      Comment

      Working...