Search Results

Search found 320 results on 13 pages for 'polymorphism'.

Page 3/13 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Learning PostgreSql: polymorphism

    - by Alexander Kuznetsov
    Functions in PL/PgSql are polymorphic, which is very different from T-SQL. Demonstrating polymorphism For example, the second CREATE FUNCTION in the following script does not replace the first function - it creates a second one: CREATE OR REPLACE FUNCTION public .GetQuoteOfTheDay ( someNumber INTEGER ) RETURNS VARCHAR AS $body$ BEGIN RETURN 'Say my name.' ; END ; $body$ LANGUAGE plpgsql ; CREATE OR REPLACE FUNCTION public .GetQuoteOfTheDay ( someNumber REAL ) RETURNS VARCHAR AS $body$ BEGIN RETURN...(read more)

    Read the article

  • Function like C# properties?

    - by alan2here
    I was directed here from SO as a better stack exchange site for this question. I've been thinking about the neatness and expression of C# properties over functions, although they only currently work where no parameters are used, and wondered. Is is possible, and if so why not, to have a stand alone function like C# property. For example: public class test { private byte n = 4; public test() { func = 2; byte n2 = func; func; } private byte func { get { return n; } set { n = value; } func { n++; } } } edit: Sorry for the vagueness first time round. I'm going to add some info and motivation. The 'n++' here is just a simple example, a placeholder, it's not intended to be representative of the actual code that would be used. I'm also looking at this from the point of view of looking at the property command as is, not in the context of using it for 'get_xyz' and 'set_xyz' member functions, which is certainly useful, but of instead comparing it more abstractly to functions and other programic elements. A 'get' property can be used instead of a function that takes no parameters, and syntactically they are perhaps only aesthetically, but as I see it noticeably nicer. However, properties also add the potential for an extra layer of polymorphism, one that relates to the 'func = 4;' getting, 'int n = func;' setting or 'func;' function like context in which they are used as well as the more common parameter based polymorphism. Potentially allowing for a lot of expression and contextual information reguarding how other would use your functions. As in many places uses and definitions would remain the same, it shouldn't break existing code. private byte func { get { } get bool { } set { } func { } func(bool) { } func(byte, myType) { } // etc... } So a read only function would look like this: private byte func { get { } } A normal function like this: private void func { func { } } A function with parameter polymorphism like this: private byte func { func(bool) { } func(byte, myType) { } } And a function that could return a value, or just compute, depending on the context it is used, that also has more conventional parameter polymorphism as well, like so: private byte func { get { } func(bool) { } func(byte, myType) { } }

    Read the article

  • Does C++ support subtyping?

    - by the_naive
    I know it might be a silly question to ask, but I didn't quite get an a absolute clear answer on this matter, so I thought I'd put it here. Does c++ support the subtyping in the sense that it fulfills Liskov's principle fully? I understand how parametric polymorphism, inclusion polymorphism(subclassing and overriding) work in c++ but I'm not entirely sure or understand if subtyping exists in the context of C++. Could you please explain?

    Read the article

  • PHP - Code Sample - Polymorphism Implementation - How to allow for expansion?

    - by darga33
    I've read numerous SO posts about Polymorphism, and also the other really good one at http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/ Good stuff!!! I'm trying to figure out how a seasoned PHP developer that follows all the best practices would accomplish the following. Please be as specific and detailed as possible. I'm sure your answer is going to help a lot of people!!! :-) While learning Polymorphism, I came across a little stumbling block. Inside of the PDFFormatter class, I had to use (instanceof) in order to figure out if some code should be included in the returned data. I am trying to be able to pass in two different kinds of profiles to the formatter. (needs to be able to handle multiple kinds of formatters but display the data specific to the Profile class that is being passed to it). It doesn't look bad now, but imagine 10 more kinds of Profiles!! How would you do this? The best answer would also include the changes you would make. Thanks sooooooo much in advance!!!!! Please PHP only! Thx!!! File 1. FormatterInterface.php interface FormatterInterface { public function format(Profile $Profile); } File 2. PDFFormatter.php class PDFFormatter implements FormatterInterface { public function format(Profile $Profile) { $format = "PDF Format<br /><br />"; $format .= "This is a profile formatted as a PDF.<br />"; $format .= 'Name: ' . $Profile->name . '<br />'; if ($Profile instanceof StudentProfile) { $format .= "Graduation Date: " . $Profile->graduationDate . "<br />"; } $format .= "<br />End of PDF file"; return $format; } } File 3. Profile.php class Profile { public $name; public function __construct($name) { $this->name = $name; } public function format(FormatterInterface $Formatter) { return $Formatter->format($this); } } File 4. StudentProfile.php class StudentProfile extends Profile { public $graduationDate; public function __construct($name, $graduationDate) { $this->name = $name; $this->graduationDate = $graduationDate; } } File 5. index.php //Assuming all files are included...... $StudentProfile = new StudentProfile('Michael Conner', 55, 'Unknown, FL', 'Graduate', '1975', 'Business Management'); $Profile = new Profile('Brandy Smith', 44, 'Houston, TX'); $PDFFormatter = new PDFFormatter(); echo '<hr />'; echo $StudentProfile->format($PDFFormatter); echo '<hr />'; echo $Profile->format($PDFFormatter);

    Read the article

  • How is covariance cooler than polymorphism...and not redundant?

    - by P.Brian.Mackey
    .NET 4 introduces covariance. I guess it is useful. After all, MS went through all the trouble of adding it to the C# language. But, why is Covariance more useful than good old polymorphism? I wrote this example to understand why I should implement Covariance, but I still don't get it. Please enlighten me. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sample { class Demo { public delegate void ContraAction<in T>(T a); public interface IContainer<out T> { T GetItem(); void Do(ContraAction<T> action); } public class Container<T> : IContainer<T> { private T item; public Container(T item) { this.item = item; } public T GetItem() { return item; } public void Do(ContraAction<T> action) { action(item); } } public class Shape { public void Draw() { Console.WriteLine("Shape Drawn"); } } public class Circle:Shape { public void DrawCircle() { Console.WriteLine("Circle Drawn"); } } public static void Main() { Circle circle = new Circle(); IContainer<Shape> container = new Container<Circle>(circle); container.Do(s => s.Draw());//calls shape //Old school polymorphism...how is this not the same thing? Shape shape = new Circle(); shape.Draw(); } } }

    Read the article

  • Generics and Constrained Polymorphism versus Subtyping

    - by Rahul G
    Hullo all. In this (Warning: PDF) presentation on Haskell Type Classes, on slide #54, there's this question: Open Question: In a language with generics and constrained polymorphism, do you need subtyping too? My questions are: How do generics and constrained polymorphism make subtyping unnecessary? If generics and constrained polymorphism make subtyping unnecessary, why does Scala have subtyping?

    Read the article

  • Polymorphism and passing

    - by Tucker Morgan
    Ok i am going to try and state my question as clearly as possible, but if you have trouble understanding it please just ask for clarification, i really want to figure out how to do this. I am writing a text based RPG, and i have three class that inherit from a super class, they all have special attacks that they can preform, at the same time i have a class that holds the function which handles battles in my game. Now how do i get the unique special abilities functions for whatever role the player chooses into the battle function. Also i am using the vector.push_back method to handle how my sub classes are referenced Please help me your my only hope

    Read the article

  • polymorphism, inheritance in c# - base class calling overridden method?

    - by Andrew Johns
    This code doesn't work, but hopefully you'll get what I'm trying to achieve here. I've got a Money class, which I've taken from http://www.noticeablydifferent.com/CodeSamples/Money.aspx, and extended it a little to include currency conversion. The implementation for the actual conversion rate could be different in each project, so I decided to move the actual method for retrieving a conversion rate (GetCurrencyConversionRate) into a derived class, but the ConvertTo method contains code that would work for any implementation assuming the derived class has overriden GetCurrencyConversionRate so it made sense to me to keep it in the parent class? So what I'm trying to do is get an instance of SubMoney, and be able to call the .ConvertTo() method, which would in turn use the overriden GetCurrencyConversionRate, and return a new instance of SubMoney. The problem is, I'm not really understanding some concepts of polymorphism and inheritance yet, so not quite sure what I'm trying to do is even possible in the way I think it is, as what is currently happening is that I end up with an Exception where it has used the base GetCurrencyConversionRate method instead of the derived one. Something tells me I need to move the ConvertTo method down to the derived class, but this seems like I'll be duplicating code in multiple implementations, so surely there's a better way? public class Money { public CurrencyConversionRate { get { return GetCurrencyConversionRate(_regionInfo.ISOCurrencySymbol); } } public static decimal GetCurrencyConversionRate(string isoCurrencySymbol) { throw new Exception("Must override this method if you wish to use it."); } public Money ConvertTo(string cultureName) { // convert to base USD first by dividing current amount by it's exchange rate. Money someMoney = this; decimal conversionRate = this.CurrencyConversionRate; decimal convertedUSDAmount = Money.Divide(someMoney, conversionRate).Amount; // now convert to new currency CultureInfo cultureInfo = new CultureInfo(cultureName); RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID); conversionRate = GetCurrencyConversionRate(regionInfo.ISOCurrencySymbol); decimal convertedAmount = convertedUSDAmount * conversionRate; Money convertedMoney = new Money(convertedAmount, cultureName); return convertedMoney; } } public class SubMoney { public SubMoney(decimal amount, string cultureName) : base(amount, cultureName) {} public static new decimal GetCurrencyConversionRate(string isoCurrencySymbol) { // This would get the conversion rate from some web or database source decimal result = new Decimal(2); return result; } }

    Read the article

  • What is upcasting/downcasting?

    - by acidzombie24
    When learning about polymorphism you commonly see something like this class Base { int prv_member; virtual void fn(){} } class Derived : Base { int more_data; virtual void fn(){} } What is upcasting or downcasting? Is (Derived*)base_ptr; an upcast or downcast? I call it upcast because you are going away from the base into something more specific. Other people told me it is a downcast because you are going down a hierarchy into something specific with the top being the root. But other people seem to call it what i call it. When converting a base ptr to a derived ptr is it called upcasting or downcasting? and if someone can link to an official source or explain why its called that than great.

    Read the article

  • Is there a way to avoid type-checking in this scenario?

    - by Prog
    I have a class SuperClass with two subclasses SubClassA and SubClassB. I have a method in a different class which takes a SuperClass parameter. The method should do different things depending on the type of the object it receives. To illustrate: public void doStuff(SuperClass object){ // if the object is of type SubClassA, do something. // if it's of type SubClassB, do something else. } I want to avoid type-checking (i.e. instanceof) because it doesn't feel like proper OO design. But I can't figure out how to employ Polymorphism to elegantly solve this problem. How can I solve this problem elegantly?

    Read the article

  • Polymorphism problem: How to check type of derived class?

    - by malymato
    Hi, this is my first question here :) I know that I should not check for object type but instead use dynamic_cast, but that would not solve my problem. I have class called Extension and interfaces called IExtendable and IInitializable, IUpdatable, ILoadable, IDrawable (the last four are basicly the same). If Extension implements IExtendable interface, it can extend itself with different Extension objects. The problem is that I want to allow the Extension which implements IExtendable to extend only with Extension that implements the same interfaces as the original Extension. You probably don't unerstand that mess so I try to explain it with code: class IExtendable { public: IExtendable(void); void AddExtension(Extension*); void RemoveExtensionByID(unsigned int); vector<Extension*>* GetExtensionPtr(){return &extensions;}; private: vector<Extension*> extensions; }; class IUpdatable { public: IUpdatable(void); ~IUpdatable(void); virtual void Update(); }; class Extension { public: Extension(void); virtual ~Extension(void); void Enable(){enabled=true;}; void Disable(){enabled=false;}; unsigned int GetIndex(){return ID;}; private: bool enabled; unsigned int ID; static unsigned int _indexID; }; Now imagine the case that I create Extension like this: class MyExtension : public Extension, public IExtendable, public IUpdatable, public IDrawable { public: MyExtension(void); virtual ~MyExtension(void); virtual void AddExtension(Extension*); virtual void Update(); virtual void Draw(); }; And I want to allow this class to extend itself only with Extensions that implements the same interfaces (or less). For example I want it to be able to take Extension which implements IUpdatable; or both IUpdatable and IDrawable; but e.g. not Extension which implements ILoadable. I want to do this because when e.g. Update() will be called on some Extension which implements IExtendable and IUpdateable, it will be also called on these Extensions which extends this Extension. So when I'm adding some Extension to Extension which implements IExtendable and some of the IUpdatable, ILoadable... I'm forced to check if Extension that is going to be add implements these interfaces too. So In the IExtendable::AddExtension(Extension*) I would need to do something like this: void IExtendable::AddExtension(Extension* pEx) { bool ok = true; // check wheather this extension can take pEx // do this with every interface if ((*pEx is IUpdatable) && (*this is_not IUpdatable)) ok = false; if (ok) this->extensions.push_back(pEx); } But how? Any ideas what would be the best solution? I don't want to use dynamic_cast and see if it returns null... thanks

    Read the article

  • Does C++ have a static polymorphism implementation of interface that does not use vtable?

    - by gilbertc
    Does C++ have a proper implementation of interface that does not use vtable? for example class BaseInterface{ public: virtual void func() const = 0; } class BaseInterfaceImpl:public BaseInterface{ public: void func(){ std::cout<<"called."<<endl; } } BaseInterface* obj = new BaseInterfaceImpl(); obj->func(); the call to func at the last line goes to vtable to find the func ptr of BaseInterfaceImpl::func, but is there any C++ way to do that directly as the BaseInterfaceImpl is not subclassed from any other class besides the pure interface class BaseInterface? Thanks. Gil.

    Read the article

  • How to mimic polymorphism in classes with template methods (c++)?

    - by davide
    in the problem i am facing i need something which works more or less like a polymorphic class, but which would allow for virtual template methods. the point is, i would like to create an array of subproblems, each one being solved by a different technique implemented in a different class, but holding the same interface, then pass a set of parameters (which are functions/functors - this is where templates jump up) to all the subproblems and get back a solution. if the parameters would be, e.g., ints, this would be something like: struct subproblem { ... virtual void solve (double& solution, double parameter)=0; } struct subproblem0: public subproblem { ... virtual void solve (double& solution, double parameter){...}; } struct subproblem1: public subproblem { ... virtual void solve (double* solution, double parameter){...}; } int main{ subproblem problem[2]; subproblem[0] = new subproblem0(); subproblem[1] = new subproblem1(); double argument0(0), argument1(1), sol0[2], sol1[2]; for(unsigned int i(0);i<2;++i) { problem[i]->solve( &(sol0[i]) , argument0); problem[i]->solve( &(sol1[i]) , argument1); } return 0; } but the problem is, i need the arguments to be something like Arg<T1,T2> argument0(f1,f2) and thus the solve method to be something of the likes of template<T1,T2> solve (double* solution, Arg<T1,T2> parameter) which cant obviously be declared virtual ( so cant be called from a pointer to the base class)... now i'm pretty stuck and don't know how to procede...

    Read the article

  • Two components offering the same functionality, required by different dependencies

    - by kander
    I'm building an application in PHP, using Zend Framework 1 and Doctrine2 as the ORM layer. All is going well. Now, I happened to notice that both ZF1 and Doctrine2 come with, and rely on, their own caching implementation. I've evaluated both, and while each has its own pro's and cons, neither of them stand out as superior to the other for my simple needs. Both libraries also seem to be written against their respective interfaces, not their implementations. Reasons why I feel this is an issue is that during the bootstrapping of my application, I have to configure two caching drivers - each with its own syntax. A mismatch is easily created this way, and it feels inefficient to set up two connections to the caching backend because of this. I'm trying to determine what the best way forward is, and would welcome any insights you may be able to offer. What I've thought up so far are four options: Do nothing, accept that two classes offering caching functionality are present. Create a Facade class to stick Zend's interface onto Doctrine's caching implementation. Option 2, the other way around - create a Facade to map Doctrine's interface on a Zend Framework backend. Use multiple-interface-inheritance to create one interface to rule them all, and pray that there aren't any overlaps (ie: if both have a "save" method, they'll need to accept params in the same order due to PHP's lack of proper polymorphism). What option is best, or is there a "None of the above" variant that I'm not aware of?

    Read the article

  • Confusion about inheritance

    - by Samuel Adam
    I know I might get downvoted for this, but I'm really curious. I was taught that inheritance is a very powerful polymorphism tool, but I can't seem to use it well in real cases. So far, I can only use inheritance when the base class is an abstract class. Examples : If we're talking about Product and Inventory, I quickly assumed that a Product is an Inventory because a Product must be inventorized as well. But a problem occured when user wanted to sell their Inventory item. It just doesn't seem to be right to change an Inventory object to it's subtype (Product), it's almost like trying to convert a parent to it's child. Another case is Customer and Member. It is logical (at least for me) to think that a Member is a Customer with some more privileges. Same problem occurred when user wanted to upgrade an existing Customer to become a Member. A very trivial case is the Employee case. Where Manager, Clerk, etc can be derived from Employee. Still, the same upgrading issue. I tried to use composition instead for some cases, but I really wanted to know if I'm missing something for inheritance solution here. My composition solution for those cases : Create a reference of Inventory inside a Product. Here I'm making an assumption about that Product and Inventory is talking in a different context. While Product is in the context of sales (price, volume, discount, etc), Inventory is in the context of physical management (stock, movement, etc). Make a reference of Membership instead inside Customer class instead of previous inheritance solution. Therefor upgrading a Customer is only about instantiating the Customer's Membership property. This example is keep being taught in basic programming classes, but I think it's more proper to have those Manager, Clerk, etc derived from an abstract Role class and make it a property in Employee. I found it difficult to find an example of a concrete class deriving from another concrete class. Is there any inheritance solution in which I can solve those cases? Being new in this OOP thing, I really really need a guidance. Thanks!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >