Thread: class polymorphysm and inheritance

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    62

    class polymorphysm and inheritance

    hi, I'm developing a numerical tool and wanted to figure out a way to restructure some of my code. So here is what I want to do:

    I want to create several (sub-)classes (model_1,model_2,...) that have the same member functions (with the same name I mean) and that share some characteristic that lets me decide which model I want at runtime. class functions will then be called using the chosen class. So a mock up of what I would want is:

    Code:
    int choice;
    getinput(choice,"filename.txt"); //the file declares which model to use
    
    //class model_* declaration (this is what I have no idea how to do)
    model_ potential;
    switch (choice){
      case (1): /*potential=model_1*/ break;
      case (2): /*potential=model_2*/ break;
      //etc...
    }
    
    potential.generate();
    potential.check_stability();
    //etc...
    Hopefully I made myself clear. I've been reading into inheritance but from what I've gathered its not what I'm looking for. My objective is to decide which class (or sub-class if there is such a thing) at runtime. knowing that all option will need to be compliant with the posterior function calls.

    I was hoping someone could point me to what I could use to accomplish this.

    thanks in advance for any help I get

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Based on this, I would say polymorphism (which goes with inheritance) is ideal for you.
    You design a base class which contains the desired interface (use virtual functions). Then you make all your functions take a pointer to the base class.
    Then you derive classes from the base and implement those virtual functions. In your choice, you can create the derived classes and store them into a pointer to base.
    When your functions deal with the base class pointer, the compiler will automatically call the right derived function.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You're wrong, killme. Inheritance and polymorphism (or concepts related to them, in non-object-oriented languages) are key ingredients of any design to address your problem.

    Generally speaking, you need to look up the "factory pattern". This is a general description of how to do what you want. There are various ways of implementing such a pattern in C++.

    However, if you don't understand inheritance and polymorphism, a description of any style of factory pattern won't make sense since the factory pattern relies on there being some method to select a function to be called based on type of object it is required to act on (and that is exactly what inheritance and polymorphism are about).

    I suggest you focus effort on understanding inheritance and polymorphism before you worry about the factory pattern.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    62
    Ok, thank you both. I had not realised I could pointers to the base function on the derived ones when I was reading about it. Here is my test code (feel free to suggest different approaches):

    Code:
    int main()
    {
        int choice=0;
        cout<<"chose the model:";
        cin>>choice;
    
        base* model_point=NULL;         //pointer to a "base-type" object
        switch(choice){                 //both models are "base-type"
        case(1):model_point=new model_1(12);//and can be called by a pointer to them
                break;
        case(2):model_point=new model_2;
                break;
        default:model_point=new base;
        }
    
        model_point->vfunction1();      //note to self: go refresh on pointers
    
        model_point->nonvirtual();
    
        cout<<endl<<"End of program."<<endl;
        return 0;
    }
    Code:
    class base{
    public:
        int choice;
        base();
        base(int);
        static int counter;
        virtual void vfunction1();
        void nonvirtual();
    };
    
    /*******************************************************************/
    
    class model_1:public base{
    public:
        model_1();
        model_1(int);
        void vfunction1();
    };
    
    /*******************************************************************/
    
    class model_2:public base{
    public:
        model_2();
        void vfunction1();
        void extra_function();
    };
    Code:
    int base::counter=0;
    
    base::base(){
        cout<<"base constructor"<<endl;
        counter++;
    }
    
    base::base(int base_arg){
        cout<<"base was called with an argument."<<endl;
    }
    
    void base::vfunction1(){
        cout<<"vfunction1 was called from the base."<<endl;
        choice=0;
    }
    
    void base::nonvirtual(){
        cout<<"Non-virtual called from base."<<endl;
    }
    
    /*******************************************************************/
    
    model_1::model_1(){
        cout<<"model_1 default constructor."<<endl;
        choice=11;
    }
    
    model_1::model_1(int entry){
        cout<<"entry="<<entry<<endl;
    }
    
    void model_1::vfunction1(){
        cout<<"vfunction1 call by model_1"<<endl;
    }
    
    /*******************************************************************/
    
    model_2::model_2(){
        cout<<"model_2 default constructor."<<endl;
        choice=22;
    }
    
    void model_2::vfunction1(){
        cout<<"vfunction1 call by model_2"<<endl;
    }
    
    void model_2::extra_function(){
        cout<<"model_2 extra function."<<endl;
    }
    I did notice (amongst other things) that the base constructor is always called with no arguments when declaring one of the derived classes (even if the derived class was called with an argument). Wouldn't it be more intuitive to allow "virtual constructors" as well? is there a way to do that? just wondering...

    anyway, thanks again for the help, now I just have to restructure a 4k line program that I didn't write so it can be reasonably easy to work on.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If your compiler supports C++11, you should replace NULL with nullptr and look into smart pointers (e.g. std::shared_ptr, std::unique_ptr).
    The compiler always calls the base class constructor because when you are creating a derived object, you are really creating an object which consists of two parts: one part is the base (whose functionality is inherited) and one whose functionality is the derived. You can call another base constructor by using the initializer list, but other than that, you cannot omit a call to the constructor.

    Now if you would want to simulate a virtual constructor, the usual method of doing so is a virtual "Clone" function. This basically acts as a function that clones itself and returns it as a pointer to base. I'm assuming that that is something you want to do. Virtual constructors themselves aren't possible (and shouldn't be).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Class inheritance
    By CASHOUT in forum C++ Programming
    Replies: 2
    Last Post: 07-01-2013, 08:41 AM
  2. Class Inheritance
    By leeor_net in forum C++ Programming
    Replies: 3
    Last Post: 09-24-2008, 04:37 AM
  3. Replies: 8
    Last Post: 01-13-2008, 05:57 PM
  4. Inheritance: assign base class to derived class
    By MWAAAHAAA in forum C++ Programming
    Replies: 15
    Last Post: 01-22-2007, 04:31 PM
  5. Need some help on class inheritance
    By HelpMe in forum C++ Programming
    Replies: 1
    Last Post: 05-21-2002, 03:44 PM