CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    May 2009
    Posts
    2

    Question writing code using base class, passing derived class instances

    I've been trying to figure out the following problem without success:

    I want to implement a general purpose code that operates on a base class, but when actually used, operates on derived class objects of the base class.

    Specifically, I have a parent class that defines a broad category of numbers.
    For sake of simplicity, I will call the class "number".
    Let's say that I have several derived classes like "complex" , "rational", "integer".

    I want the program to calculate a formula using the class number using member functions such as "add" "subtract" "multiply"...but I want to be able to swap in specific derived classes of "number" in the actual computation.

    static void complex :: subtract (complex &diff, complex & a, complex & b) {
    diff.real = a.real - b.real;
    diff.imaginary = a.imaginary - b.imaginary;
    }
    static void rational :: subtract (rational &diff, rational &a, rational &b) {
    // ... find common denominator
    // ... subtract
    // (actual code abbreviated)
    }
    void number :: absoluteDifference (number &result, number &a, number & b) {
    number temp; // how do I initialize this to be the right kind of derived class?

    number :: subtract (temp, a, b);
    if (number :: isNegative (temp)) { // determines if parameter temp is negative
    number :: negate (temp); // negates value in temp
    }
    number :: copy (result, temp); // copies value in temp to result
    }

    So how do I initialize temp to be the right kind of derived class of class number?
    Ok, so obviously, in the above example, I could just directly use the result object as the temporary variable and eliminate the problem. In reality, the program I want to write is much more complex and temporary workspace objects are essential.

    I would appreciate any help. Thanks.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: writing code using base class, passing derived class instances

    Have you considered generic programming using templates instead of using an inheritance hierarchy?

    So how do I initialize temp to be the right kind of derived class of class number?
    Ok, so obviously, in the above example, I could just directly use the result object as the temporary variable and eliminate the problem. In reality, the program I want to write is much more complex and temporary workspace objects are essential.
    You might need to use say a virtual clone() and/or create() member function that returns a copy/default constructed object of the specific derived class type. But have you considered that your subtract() member functions for complex and rational cannot override any member function from number since their parameters are specific to the derived classes? You will thus be unable to use polymorphism easily.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    May 2009
    Posts
    2

    Re: writing code using base class, passing derived class instances

    Thanks for your reply.
    So if I were to use polymorphism, I would have to make a function in the number class that checks the type of the specific instance of the derived class and create a copy?
    From what I find on the internet, it looks like this process is not exactly easy in C++ unlike in Java. I was hoping there were a simple and elegant way to do this but maybe no such things exist.

    But thinking about this problem again, I have an alternate solution.
    Make a clone function in each of the derived classes so that any derived class object can return a new instance of the same class. I just call that function from the derived class object passed into the function and make enough new instances of temporary objects.

    I don't quite understand the concern you raised about how I might have to forget about polymorphism and go for templates, but I will try to think about it...

    Thanks for the response and the inspiration.

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: writing code using base class, passing derived class instances

    Your subtract() functions will need to take number parameters, not the derived types---otherwise the virtual function mechanism won't work.

    You can dynamic_cast the parameters to the derived types you want inside the function. Not the most efficient way to do it, but it'll work.

    So if I were to use polymorphism, I would have to make a function in the number class that checks the type of the specific instance of the derived class and create a copy?
    Well, you could, but it would be much easier to do.....
    Make a clone function in each of the derived classes so that any derived class object can return a new instance of the same class.
    as you say. That's typically how cloneable objects are done.

    From what I find on the internet, it looks like this process is not exactly easy in C++ unlike in Java.
    A lot of C++'s approaches differ from Java's due to the lack of a God Object. For example, if both rational and complex defined operator- (subtract() would work too as you have it, but let's stick to typical C++ style), then generic code could be written using templates which included subtraction of either type with no regards to which it actually was---it could actually be *any* type defining operator-, including the primitive types----and with inheritance not entering into the picture at all.

    You could define "number" as a *concept* rather than a base class. Actually that's not fully supported in any compiler yet I think, but it will be in C++0x. It's the equivalent of an interface when dealing with templates.

  5. #5
    Join Date
    May 2009
    Posts
    28

    Re: writing code using base class, passing derived class instances

    Hi All,
    I was searching for some answers to my question and this thread seems relevant; so I m tossing it up from the past.

    Briefly, my code is as follows:
    MyProcess.h
    MyProcess.cpp

    MyClass.h
    MyClass.cpp

    Currently, MyProcess.h declares MyClass as follows: MyClass my_class; // note that it is not a pointer

    I want to change the definition of a method in MyClass, but it is in a library. So I inherit it (MyInheritedClass) and override the method. Now, I cant change the MyProcess.h file as it is shared by other projects. How do I make my_class to point to an object of MyInheritedClass. Is a statement like the following in the constructor of MyProcess.cpp legitimate?

    my_class = new MyInheritedClass();

    Is there a recommended approach to deal with this?

    Thanks,
    Shivraman

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: writing code using base class, passing derived class instances

    You are probably in a fix. Polymorphism in C++ works through pointers and references, so if my_class is of type MyClass, it is of type MyClass. You cannot make it to be of a derived class type.

    Not only that, but if MyClass was not designed to be a polymorphic base class, and thus lacks a virtual destructor, then even if my_class was of type MyClass*, using delete on my_class would result in undefined behaviour if my_class pointed to a MyInheritedClass.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    May 2009
    Posts
    28

    Re: writing code using base class, passing derived class instances

    Quote Originally Posted by laserlight View Post
    You are probably in a fix. Polymorphism in C++ works through pointers and references, so if my_class is of type MyClass, it is of type MyClass. You cannot make it to be of a derived class type.

    Not only that, but if MyClass was not designed to be a polymorphic base class, and thus lacks a virtual destructor, then even if my_class was of type MyClass*, using delete on my_class would result in undefined behaviour if my_class pointed to a MyInheritedClass.
    Thanks for your response!
    MyClass has a virtual destructor, so I guess those who wrote it did intend for it to be used as a polymorphic base class. In that case, I will go ahead with MyInheritedClass.
    (I didnt know that lack of virtual destructor is an indication that the class is not meant to be a polymorphic base class. Thanks for pointing it out)

    In this case, I will make a copy of MyProcess.h in my project and proceed.

    Thanks again!
    Shivraman

  8. #8
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: writing code using base class, passing derived class instances

    It would seem that overloaded functions & operators should do the job.

    If you were to overload the appropriate operators for your number types then the operations would be identical to normal built in types.

    Assuming this is defined...
    Code:
    Rational operator - (const Rational &lhs, const Rational &rhs)
    {
        Rational result;
        // Do the calculation.
        return result;
    }
    Code:
    // Subtract two rationals.
    Rational a;
    Rational b;
    ...
    
    Rational result = a - b;
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured