FAQ Database Discussion Community


Laravel - Eloquent - Polymorphic relationships with namespaces

laravel,polymorphism,eloquent,laravel-5
I have 2 tables related by a polimorphic relationship: The Store table: id | name | ... 15 | my_store | ... And the Tag table, that is connected to the Store table through the related_id key and the type. id | related_id | tag | created | type 1...

polymorphic methods that return different class types in Swift?

swift,polymorphism
I have a collection of heterogeneous object types (common superclass). Per element, I want to fetch a class type to instantiate. In ObjectiveC, I did something like this: @implementation CommonClass - (Class) secondaryAnnotationClass { return [MKAnnotationView class]; // abstract implementation, just return default class } @end @implementation SubclassFoo - (Class)...

Converting List of childs to List of parents in one line

java,generics,inheritance,polymorphism,java-8
Converting List of Banana to List of Fruit ... public class Fruit { } public class Banana extends Fruit { } public List<Banana> allBananas() { return new ArrayList<>(Arrays.asList(new Banana(), new Banana())); } ... before returning I have to do following two-steps-casting: public List<Fruit> getFruits() { List<? extends Fruit> fruits =...

Replacing instanceof for Java Beans

java,generics,polymorphism,instanceof
I have encountered some code in a project at work where we have JavaBeans. I have discovered a Writer object that writes these beans to file. Unfortunately this uses instanceof to ask what type the bean is, before writing to file, like so: if (bean instanceof BeanA) { writer.handleBeanA(bean); }...

C++: Polymorphic container / iterator vs compile time concept / traits

c++,polymorphism,sfinae,typetraits,c++-concepts
Background This is purely for educational purposes. If you don't want to read the whole background, you can skip to the question at the bottom. I have written a Queue interface (abstract class), and 2 derived implementations based on resizing arrays and linked lists. template <typename T> class IQueue {...

hibernate joined strategy inheritance and polymorphism

java,hibernate,polymorphism
In hibernate, when I use the joined strategy. does hibernate support polymorphism? for example: @Entity @Table(name = "PERSON") @Inheritance(strategy=InheritanceType.JOINED) public class Person { @Id @GeneratedValue @Column(name = "PERSON_ID") private Long personId; @Column(name = "FIRSTNAME") private String Fullname; public Person() { } public Person(String fullname) { this.Fullname= fullname } } and...

Class method picks hidden base class property over new subclass property

c#,polymorphism
I'm trying to write a unit test for one of my classes that uses a base class from a third party library, but my first attempt is fragile as the tests depend on integration with texts managed by content managers. First, a small repro. This will represent the third party...

Cannot use list of classes by base interface [duplicate]

c#,.net,linq,polymorphism
This question already has an answer here: C# variance problem: Assigning List<Derived> as List<Base> 4 answers My interface IDerived is inherited from IBase: public IDerived : IBase { ... } I have method which needs IList: public MyClass { public static void DoSmth(IList<IBase> bases) { ... } } But...

Context bound for nested type

scala,polymorphism,implicits
Is it possible to create somehow a context bound for a nested type? Something like this: def f[T : U[List]](a: T) Ofc, this is not Scala syntax, but illustrates what I want to achieve, that is, get a bound on an implicit U[List[T]]. Is this possible? Thanks....

C# Polymorphism/Lists

c#,list,class,object,polymorphism
I've been having trouble with this. I'll summarise briefly. I have 4 classes. One is a "Person" class. The other three are "Rental", with two classes inheriting from that, "RentalByDay" and "RentalByKM". Within the "Person" class, there is a list of Rental objects. The issue I'm having is I'm not...

C++ constructors in subclass

c++,constructor,polymorphism
hey I want to send my constructor Buttom(string) from my derived to the function setText(string) in my base , I tried to do this Buttom(string) : setText(string text){} which gives me syntax error, thanks in advance! base class: #include"RGB.h" #include"Point.h" #include"string" using namespace std; class Widget{ protected: RGB _backgroundColor,_textColor; Point...

Visual C++ - Virtual method is not overriden

c++,templates,inheritance,polymorphism,visual-studio-2015
I have two classes: template <class T> class TArray { public: TArray& operator =(const TArray &array) { return Copy(array); } virtual TArray& Copy(const TArray &array) { ... } } class TString : public TArray<TCHAR> { public: TString& Copy(const TString &string) { ... } } Classes also have needed constructors. But...

reuse/memoization of global polymorphic (class) values in Haskell

haskell,polymorphism,memoization
I'm concerned with if and when a polymorphic "global" class value is shared/memoized, particularly across module boundaries. I have read this and this, but they don't quite seem to reflect my situation, and I'm seeing some different behavior from what one might expect from the answers. Consider a class that...

Polymorphic operator<< from virtual base class

c++,inheritance,polymorphism,operator-overloading
I want to overload Operator<< to do a specialized operation within a context of polymorphic classes. To give a direct example of what I want (using int as an example): Base* a = new A; (*a) << 10; I would like to use this syntax because another portion of my...

Polymorphism and casting in Java [closed]

java,oop,polymorphism
What is the difference between the way these two objects are instantiated. Employee emp = new Employee; Employee emp = new Manager(); What are the different methods that can be accessed for each. What is downcasting and upcasting?...

C++ accessing member of subclass of abstract class pointer vector

c++,class,vector,polymorphism,abstract
Error over here: Rocket.cpp:31:16: error: no member named 'getThrust' in 'RocketPart' rocket[0]->getThrust(); When I want to access getThrust() from class Engine over the vector<RocketPart*> rocket with rocket[i]->getThrust(), I get the error message from the top of my question. What am I doing wrong? Is it possible to access it over...

How do I add Data.Bits to Data.Modular, automatically?

haskell,polymorphism,ghc
I need to xor a couple of mod numbers (from Data.Modular).... let x = 4 :: Integer `Mod` 10 y = 6 :: Integer `Mod` 10 print $ x `xor` y ....but, this doesn't work, because Mod x y is not an instance of Data.Bits. I can, or course, convert...

Instantiate polymorphic member variable to be of appropriate type

c++,polymorphism
I have a Base class which contains a member variable std::unique_ptr< Base > next. I have several derived classes of Base. I have a non-virtual function Base::grow() which initialises next. next will always point to an object of the type of the object calling grow. That next is of the...

How to use polymorphism in ArrayLists?

java,arraylist,polymorphism,covariance,contravariance
So I have this zoo program where I want to have a list of rooms in a zoo, and a list of cats in each room. I have 3 classes: Felid, Housecat and Wildcat - Housecat and Wildcat extend Felid. depending on the literal class of animal (right now I...

Trouble with dynamic array of pure base class c++

c++,arrays,dynamic,polymorphism,virtual
I have this programming assignment for an intro c++ class. The program is supposed to use virtual functions to input, calculate and display quantities associated with various shapes. The Shape class must contain all pure virtual functions: display, getdimensions, area, perimeter, and volume. The program driver must allocate an array...

Python: asking if two objects are the same class

python,polymorphism,instance
I have a class Animal and other animals inherit from it (e.q. Sheep, Wolf).I want to check if two objects are the same class and if so, it should create new object of the same class and if they are not, they are fighting. if x and y same object:...

calling a virtual function through a reference: derived class' override gets called

c++,polymorphism,dynamic-binding
I have the following code: #include <iostream> using namespace std; class Parent { public: virtual void f() { cout << "Parent" << endl; } }; class Child : public Parent { public: void f() { cout << "Child" << endl; } }; void t1(Parent * p) { p->f(); } void...

Cartesian (outer) product of lists in OCaml

list,polymorphism,tuples,ocaml
I would like to iterate over all combinations of elements from a certain number of lists which have the same length but not necessarily the same type. First I tried to write a general cartesian (outer) product function which takes a list of lists and returns a list of tuples,...

Utilizing both inheritance and polymorphism to draw images?

java,image,inheritance,polymorphism,paint
I am trying so I can have three values in the parent class (img, LocX, LocY) that are supposed to be able to change depending on which child class they are in. I want to have it so when I try to use the method to draw the player, it...

base class pointer, invoke method based on derived type

c++,oop,inheritance,polymorphism
I understand that the following code doesn't work -- can't convert base to foo. Is there something I can do, or some pattern to employ which would get me close the behavior I'm trying to achieve in the code below? IOW, if I have a base class pointer to a...

Single Table Inheritance or Polymorphic?

ruby-on-rails,ruby,activerecord,polymorphism,single-table-inheritance
So I have a database structure that looks something like this: Events: event_id: :integer event_type: :string name: :string slug: :string user_id: :integer start: :datetime finish: :datetime and Weddings which I need to inherit from Events: bride_name: :string groom_name: :string street: :string city: :string state: :string zip: :integer receptions: :text I...

How to use arrays or vectors of pointers polymorphically?

c++,arrays,polymorphism
I have read in many different posts regarding this matter, that arrays are not to be treated polymorphically and that one should use arrays of pointers instead, and the reasoning behind it is clear to me. However, I cannot find an example of how it is done and I cannot...

Laravel: Retrieve polymorphic attributes efficiently

rest,laravel,polymorphism,eloquent
My actual Question is: How to return attributes to the client which I actually need, throw the rest away and be as efficient as possible? So, I have a construction where I basically have media objects, which can be of different types, like video, picture, link and so on. This...

Defining an object with a pointer to an object and operator new in c++ [duplicate]

c++,object,polymorphism
This question already has an answer here: What are all the member-functions created by compiler for a class? Does that happen all the time? 4 answers A simple example regarding definition of objects with a pointer to an object. We define an object A *a = new A(123.4); and...

Entity framework + mvc + code first + Inheritance table per Hierarchy, How to use heritage/polymorphism to avoid switch/if

c#,entity-framework,inheritance,model-view-controller,polymorphism
I lack knowledge here, so I need help with this, cause I'm lost in concept I don't understand. First, let me introduce you the context of the question. General context We have equipments that are coming from others applications. So, we designed a database class equipment. Each applications will have...

Preventing the virtual and override in inheritance chain

c#,inheritance,polymorphism
Please note: This is a conceptual question and not related to production specific code. Suppose we have Class A with virtual method GetBonus(int value) Next, we derive a class from this called Class B. In this Class B we override the method GetBonus. Next, we derive a class from Class...

Constructing linked Java objects from constructors

java,arrays,object,inheritance,polymorphism
I've been getting frustrated trying to wrap my head around OOD. I'm trying to build a program that has three classes - one called Person which would have a constructor consisting of personal information. Another class called Doctor which inherits the Person class and simply constructs an object with an...

How to implement methods of an abstract class? (Java)

java,inheritance,polymorphism
I am trying to use the methods from an abstract class that is implementing an interface. I keep getting a null pointer exception when I call upon a method and I am not sure why. Any ideas? Thanks. package start; public class Automobile extends Vehicle { // code with main...

Initializing list of objects using polymorphism

java,list,polymorphism
I have a question on applying polymorphism: Let's assume I have a class Bird, and I have many classes that extend it (like Pigeon, Falcon and so on). Next, I have a Cage class. In this class, I want to make a list of birds which live in that cage...

Overriding properties to make them readonly - what about the setter?

c#,inheritance,properties,polymorphism,setter
I have the following design goal in a class hierarchy: There is a BaseClass defining some properties, which would usually be read/write: public class Media { public virtual object Content { get; set; } public virtual double recordingLength { get; set; } } The intention is to have some subclasses...

using derived class in runtime c++

c++,pointers,casting,polymorphism,runtime
this is checking in runtime if mybase class is a derived class. I need to call a member variable from say myDerived.member1 using myBase like myBase.member1 in runtime. Here myBase is a pointer. How to do that. if(dynamic_cast<myDerived*>(myBase)) ...

Compile Time Template restriction C++

c++,templates,inheritance,polymorphism
Basically I have 4 classes: OverVoid Meta: that inherits OverVoid Physical: which has nothing to do with the above Move: a templated class I want move's template to accept objects of only OverVoid type i.e. OverVoid and Meta. class OverVoid{ public: virtual ~OverVoid(){ }; }; class Meta: public OverVoid{ };...

Decorator Pattern Confusion?

java,polymorphism,decorator
I've been doing some research on the decorator pattern, and there is a bit of confusion with understanding one of it's problems. I keep reading that "decorators are typically transparent to the client of the component; that is, unless the client is relying on the component's concrete type". I'm not...

Java virtual method invocation

java,polymorphism
Say I have the following code: public class Employee { public int salary = 2000; public void getDetails() {...} } public class Manager extends Employee { public int salary = 5000; public int allowance = 8000; public void getDetails() {...} } and a main() that does the following: Employee emp...

Java runtime polymorphism not working with different parameter types

java,polymorphism,overloading,overriding
I have 3 different class, public class Parent { public void add(double a, double b) { System.out.println("Parent class add(double double)"); } public class Child extends Parent { public void add(long a, long b) { System.out.println("Child class add(long long)"); } } public class Test { public static void main(String arr[]) {...

Java polymorphism through injection at runtime

java,polymorphism,code-injection
I hear that in Java I can achieve polymorphism through injection at runtime. Can someone please show a simple example of how that is done? I search online but I can't find anything: maybe I am searching wrong. So I know about polymorphism through interface and and extension such as...

Virtual method being called using base

c#,polymorphism,override,virtual
In regards to a virtual method: protected internal virtual void PopulateGetParameters( int id, List<SqlParameter> parameters) { } Which is being overridden in a class inheriting the base class. What is confusing me is the overriding method is calling back to the the virtual method? protected override void PopulateGetParameters( int id,...

Using traits as types in enums

enums,polymorphism,rust,traits
Here's my code: trait UnaryOperator { fn apply(&self, expr: Expression) -> Expression; } pub enum Expression { UnaryOp(UnaryOperator, Expression), Value(i64) } Which gives the following errors: error: the trait 'core::marker::sized' is not implemented for type 'parser::UnaryOperator' note: 'parser::UnaryOperator' does not have a constant size known at compile-time I'm not sure...

C++ prevent inherit specific public member of base class

c++,inheritance,polymorphism
How can I prevent a public member to be inherited by it's derived class? Like, if I have this: class Person { public: enum { MALE, FEMALE, BOTH }; Person(std::string name, int gender) : _name(name) { switch (gender) { /* processing here */ } } protected: std::string _name; }; class...

Java polymorphism - Reference variables issue [closed]

java,casting,polymorphism,up-casting
I am learning java and polymorphism. I am using book head start with java. I was trying to experiment with them. I learned that methods you can call depends upon the reference object.So I created this code package animals; public class AnimalstestDrive { static public Animals[] myZoo = new Animals[5];...

Difference between runtime and compile time polymorphism in c++

c++,polymorphism
I'm confused between these two polymorphism please help me out by giving simple examples as a i'm totally new to c++.Give me some basic idea only.

Why am I able to access a private instance variable of one instance from a method invoked on another instance of the same object? [duplicate]

java,oop,inheritance,polymorphism,modifier
This question already has an answer here: How is this private variable accessible? [duplicate] 5 answers In the below code: class Person { private String name; private int x = 5; public Person(String name) { this.name = name; } public void invoke(Person p) { System.out.println(p.name); } } class YU...

basic java code to understand inheritance

java,inheritance,polymorphism
Why does the System.out.println(b.h + " " + b.getH()); prints the following: Beta 44 <br/> 4 44 (notice this is in the second line) I was expecting it to print something like this: 4 Beta 44 44 (this one is in one line) The reason why I thought it would...

Confused with inherited functions

c++,inheritance,polymorphism
Fixed: modified as such: 3rd code piece, 1st line: static void writeFile(User &user) User class: User class: void print() made public Now it works as intended. Thanks to everyone that helped. This is the original post: 1. class User { 2. protected: 3. string name; 4. string surname; 5. ....

Implementing Polymorphism in Javascript - how would this look?

javascript,polymorphism
I'm trying to make the jump to a more OOP style javascript approach, but I have just not gotten it right in javascript. Take the following function as an example. function positionalCSS(array, cs, lcs){ /* Define css for circle based on number of circles */ //Count array var arrCount =...

Using a typeclass to access fields of similar data types in Haskell

haskell,graph,polymorphism,typeclass
I am in the process of working on some graph problems in Haskell. In the middle of my work, I decided that I wanted to be able to represent edge colors within a graph data type. So I started with edges: Edges could be either colored or uncolored. Here's a...

Can anyone tell me why am having Null for the object Staff and how can I fix it

inheritance,arraylist,polymorphism
I have a class called main, and Staff that inherits from Person2 1) I should create an ArrayList that holds objects of type Staff 2) Then create Staff object using Person2 class and insert it in the list 3) Make user enter data for staff object then print it I...

Unable to use variable(s) from parent class?

java,image,inheritance,model-view-controller,polymorphism
So I need to have an example of inheritance in this code, and I am trying to get it so I instantiate private BufferedImage image in the parent class, and then have it take on different forms within the child classes such as Player, Enemy, and possibly Key. They will...

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

java,json,compiler-errors,polymorphism,jackson
I am attempting to work through a tutorial from Programmer Bruce that is supposed to allow the deserialization of polymorphic JSON. The complete list can be found here Programmer Bruce tutorials (Great stuff btw) I have worked through the first five with no problems but I have hit a snag...

C++ polymorphic class pointer in vector

c++,pointers,vector,polymorphism
Let's say I have the following code which, in short, has: a BaseClass with a pointer to a PointerClass a ChildClass that inherits from BaseClass a HolderClass that has an std::vector of ChildClasss and an std::vector of BaseClass*s: The entire code is as follows: #include <stdlib.h> #include <time.h> #include <vector>...

How do you pull specific objects from an arraylist?

java,inheritance,arraylist,polymorphism,method-overriding
I've made an Animal superclass, Shark and Whale subclasses. What would I use to print out just the Shark objects from this arraylist? Driver: import java.util.ArrayList; public class Creator { public static void main(String[] args){ ArrayList<Animal> obj = new ArrayList<Animal>(); obj.add(new Shark("James")); obj.add(new Shark("Mike")); obj.add(new Whale("Steve")); obj.add(new Whale("Tommy")); for (Animal...

I am having problems understanding inheritance and getting multiple classes to work together?

c++,inheritance,polymorphism
This is an assignment for my class. I am supposed to have two classes--salaried and hourly-- which both need to inherit from another class employee. When I compile my code I get no errors but when I run my program, only the header and the netpay functions produce any output....

C++: saving derived class in shared_ptr of base class

c++,c++11,polymorphism,shared-ptr
I want to have a class that has a shared pointer as member: class MyClass { public: shared_ptr<MyAbstractBaseClass> myPointer; } How can I make the pointer point to an instance of a derived class?...

C++ Inheritance and Polymorphism unknown output

c++,inheritance,polymorphism
#include "stdafx.h" #include <iostream> using namespace std; class Base { // Define a base class public: virtual void Func1() = 0; virtual void Func2(); virtual void Func3(); void Func4(); }; class A : public Base { // Class A derives from Base public: void Func2(); virtual void Func4(); }; class...

Why is this downcast not allowed in java?

java,oop,polymorphism,downcast
Let's say I have a superclass of Animal, and a subclass of Dog. We can upcast by saying: Animal a = new Dog(); We CANNOT downcast by saying: Dog b = new Animal(); So I do understand that an animal does not HAVE to be a dog. But, why would...

Best way to switch between subclasses / interface implementations based on type?

polymorphism
let's say we have something like this: abstract class Object { void foo(){ ... } } class ObjectA extends Object { ... } class ObjectB extends Object { ... } class ObjectC extends Object { ... } What's the best way to switch between a set of extended classes based...

generic parent class as a polymorphic variable in a list

java,generics,polymorphism
I'm wondering if it's possible to use a generic parent class as a polymorphic variable in a list. My terminology here may not be correct, so bellow is some code that outlines essentially what i'm trying to do. abstract class parent<T> { private T var; abstract T evaluate(); } class...

Haskell ad hoc polymorphism

haskell,polymorphism,overloading,typeclass
I'm trying to get my head around ad-hoc polymorphism in haskell, that is having the same function provide different behaviour for different argument types. But while the following test code compiles {-# LANGUAGE MultiParamTypeClasses #-} class MyClass a b where foo :: a -> b instance MyClass Bool Int where...

Multiple Dispatch: A conceptual necessity?

oop,design-patterns,polymorphism,dynamic-dispatch,multiple-dispatch
I wonder if the concept of multiple dispatch (that is, built-in support, as if the dynamic dispatch of virtual methods is extended to the method's arguments as well) should be included in an object-oriented language if its impact on performance would be negligible. Problem Consider the following scenario: I have...

Scheme define-macro and/or define-syntax

macros,polymorphism,scheme,overloading
I want to create an overloaded Scheme macro for a simple form of polymorphism. That is, a macro smart enough to expand differently when given params of different types, so that (look-up key container) does the "right" thing for different kinds of containers. (define-macro (look-up key container) (cond ((table? container)...

How to properly override virtual method to add functionality?

c++,qt,oop,polymorphism
In base class I have simple remove by id virtual function, however in derived class I need also emit a signal (notify) after removing. In base class. Below is the default implementation of function void Ui::GameEntityList::remove_games_by_sport_id_virt(const QString &sport_id) { for(QList<GameEntity*>::iterator it = m_game_list.begin(); it != m_game_list.end();) { GameEntity* tmp =...

Best practice to set large amount of properties in C# base class from derived class

c#,inheritance,polymorphism
I'm working on refactoring some legacy code, and have a large set of data objects that share the same properties and fields. I'm also doing some reading on refactoring and at first glance it looks like I should use Extract Superclass. Is this a good idea when all I'm combining...

Java Passing objects to a method

java,polymorphism
Suppose that X and Y are classes such that Y extends X. Also, let method(X xObj) be a method of X. Why does the following code compile? X xObj = new X(); Y yObj = new Y(); xObj.method(yObj); Also, are there other similar cases in which code that seems incorrect...

Actual class of object reference

java,oop,inheritance,polymorphism,instanceof
Given three classes A, B, and C, where B is a subclass of A, and C is a subclass of B. (a) (o instanceof B) && (!(o instanceof A)) (b) (o instanceof B) && (!(o instanceof C)) (c) !((o instanceof A) || (o instanceof B)) (d) (o instanceof B) (e)...

Is there anything similar to JavaScript's “prototype” in Java?

java,javascript,inheritance,polymorphism,prototype
Right, so I know Java fairly well but I never studied extensively into JavaScript. I was chatting with an acquaintance who knows JavaScript, but who has not studied into Java. He was telling me about the advantages of JavaScript over Java in terms of how it functions but not its...

Is C++ virtual definition inherited automatically?

c++,polymorphism,virtual
Is C++ virtual definition recursive? Consider class Foo { public: virtual void a()=0; }; class Bar:public Foo { public: void a() { //... } }; If I now inherit Bar and overload a again, is that a also polymorphic? Recursive means that Given a class A that has a virtual...

C# Polymorphism and Method Inheritance

c#,polymorphism
Consider the following classes: public class X {}; public class Y : X {}; public class Z : X {}; public class A { public bool foo (X bar) { return false; } }; public class B : A { public bool foo (Y bar) { return true; } };...

c++ member function polymorphism issue

c++,oop,inheritance,polymorphism
I'm experiencing troubles with c++ inherrited member function, look at the following code: binIO_t wtest(path, mode); const void* Buff = "abcd"; wtest << Buff, 1; //no operator found wtest.virtIO_t::operator<<(Buff), 1; //works fine Exact compiler error is: Error 1 error C2679: binary '<<' : no operator found which takes a right-hand...

Better way to call a generic function in the derive class

c#,generics,inheritance,polymorphism
I wonder is there a way to setup my Base class so that I won't need to override the derive class when calling Activate(). It is calling the same function with the generic type of the derive class. public abstract class Base { public abstract void Activate(); } public class...

How to implement pure virtual functions with different parameter structures

c++,polymorphism,virtual,abstract,pure-virtual
I'm building a class with pure virtual functions called Database. The idea is to have a class that handles all the database interfaces (ie: open and close) and can be used on my business layers. The Database class will be implemented in several 'flavours' for different databases, like mySqlDatabase and...

python: Function pointer breaks polymorphism

python,polymorphism,function-pointers
I would like to store a dict of function signatures in a base class and have child classes override some of these function signatures. However, it seems like my implementation breaks polymorphism. I want some suggestions on an elegant alternative. Thanks! class Base: def __init__(self, key): self.FXN[key](self) def f(self): pass...

Returning `this` in a super method of inherited class

java,inheritance,polymorphism,this
let's say i have class A and class B which extends A, here are the classes: A: public class A { public int x; public static int y; public A(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public static...

Is there a way to cast an abstract object to its child? [duplicate]

c++,inheritance,polymorphism
This question already has an answer here: C++ cast to derived class 4 answers Let's imagine a situation where I have an abstract class named 'Base' with a virtual pure method named foo(), and 2 children (Inherited1 and Inherited2) that both implement this method in their own way. Now...

Type Family Polymorphism

haskell,polymorphism,type-families
So I have a function apply :: proxy tf -> tf Int -> tf Int which takes a Proxy intended to carry a type family and applies Int to that type family to determine the type of the second argument and return value. However, I'm getting some confusing responses from...

How to enforce parent / derived relationship of two independent classes inside a container?

c++,pointers,polymorphism,containers,vtable
Consider the following class definitions: #include <string> class CParty { public: CParty(); virtual ~CParty(); int m_nId; }; class CPartyEx : public CParty { public: CPartyEx(); ~CPartyEx(); std::string m_sName; }; class CTransaction { public: CTransaction(); virtual ~CTransaction(); int m_nClassNo; }; class CTransactionEx : public CTransaction { public: CTransactionEx(); ~CTransactionEx(); std::string m_sDesc;...

Function overriding in Java vs C++

java,c++,polymorphism,override
Two similar definitions in Java and C++, but totally different behaviour. Java version: class base{ public void func1(){ func2(); } public void func2(){ System.out.println(" I am in base:func2() \n"); } } class derived extends base{ public void func1(){ super.func1(); } public void func2(){ System.out.println(" I am in derived:func2() \n"); }...

What would be the correct design here (encapsulation, polymorphism, inheritance)?

oop,inheritance,design-patterns,polymorphism,encapsulation
Assuming I have an interface and 3 or 4 classes that implement the interface. Now let's say I have another method but it is relevant only for one or two implementing classes. So as I see it there are two approaches Declare the method in the interface, implement in all...

Java OOP polymorphism design/issue

java,oop,polymorphism
I am creating a very basic Cache object. Here is my code: Cache.java is an abstract class meant to be overriden. public abstract class Cache { protected Date dateCreated; protected long expiration; private BuildStrategy strategy; protected Cache(long expiration, BuildStrategy strategy) { this.dateCreated = new Date(); this.expiration = expiration; this.strategy =...

C++ call a child's method from a vector of parents?

c++,class,inheritance,polymorphism
Say that you have the following class: class Parent { // methods and members go here }; then you create a child based on the parent: class Child : public Parent { public: someFunction(); }; Now class Parent doesn't have someFunction() but class Child does. Say that you have a...

Why can't class be destructed in polymorphism C++

c++,inheritance,polymorphism
I have the problem with using the polymorphism. The code here: class A { public: A() {cout << "construct a" << endl;} virtual ~A() {cout << "destroy a" << endl;} }; class B : public A{ public: B() {cout << "construct b" << endl;} ~B() {cout << "destroy b" <<...

boost serialize polymorphic class

c++,serialization,boost,polymorphism,abstract
With the following example I attempting to learn a few new to me concepts. abstraction polymorphic classes factory programming. boost serialization The nuances of how pointers behave are still something I am working to figure out. Here is a small program that I have written to show you the issue...

Java dynamic, static casting

java,dynamic,static,polymorphism
import javax.swing.*; public class Toast { static Object[] objects = { new JButton(), new String("Example"), new Object() }; public static void main(String[] args) { System.out.println( new Count(objects) ); for (Object o : objects) System.out.println(o); } } class Count { int b, s, o; public Count(Object[] objects) { for (int i=0;...

C++ Understanding Functors Polymorphism

c++,polymorphism,functor
I try to implement polymorphic functor objects (pure abstract base class and children) for understanding purposes only. My goal is to create many objects of the base class that use different implementations of the pure virtual functions. When I create a pointer of the base class and set it equal...

How do I properly organize my inheritance classes to take advantage of polymorphism?

c++,qt,inheritance,polymorphism
I am trying to redesign my item class. I am having trouble picturing how things should work. Current implementation: class Item : public QGraphicsItem { public: typedef enum { PolygonType = QGraphicsItem::UserType + 1 } ShapeType; Item() {...} Item(const Item &copyItem) // copy constructor { m_shapeType = copyItem.getItemShape(); m_color =...

Inheritance and Polymorphism in C#

c#,inheritance,polymorphism
There's a simple question, What will the program print to the console? I never thought that I could be wrong as much as I was with this piece of code. It behaved the other way around of what my logic expected from it. If someone could please enlighten the reason...

Polymorphism in C#. Base Class's Method is Called But Why? [duplicate]

c#,inheritance,polymorphism,override,virtual
This question already has an answer here: C# virtual keyword 9 answers Most of the articles I read about Polymorphism of methods in an inheritance hierarchy does not provide a reason why this happens. Can someone please provide a reason or analogy of the following behavior? Class A{ public...

Returning an unknown object

c#,class,polymorphism
As an example, I have a base class called baseAbstractClass and a couple of derived classes: public class Derived : baseAbstractClass { public Derived() { } // abstract methods go here } public class DerivedEx : baseAbstractClass { // code goes here } and I have this class: public class...

How to read objects (Polymorphic) of the chosen class, from the XML using JAX-B

java,list,jaxb,polymorphism
I created a list of polymorphic objects. I can convert them into XML and vice versa (marshall and unmarshal using JAXB.) But I would like to read only the objects from the chosen class. I used a few tutorials about converting object lists by JAXB, for example this one: http://memorynotfound.com/convert-xml-to-polymorphic-object-using-jax-b/...

Slimming down polymorphic controller; where does the logic belong?

ruby-on-rails,polymorphism
I am implementing my own RESTful voting system. 'Questions' and 'Answers' are both votable. Votes are created, updated and deleted. When an action is preformed on a voteable, the voteable's class is passed as a param. The controller needs to look at the votable_type to retrieve the correct votable object...

Generate permutations using polymorphic method

c#,polymorphism,permutation
I was recently asked to write a piece of code as part of an interview test. The instructions were : Please write a piece of code that takes as an input a list in which each element is another list containing an unknown type and which returns a list of...

Returning the type of an inherited class

c#,generics,polymorphism
Consider: class BasicType { public BasicType() { } public T Save<T>() where T : BasicType { BasicType b = DataContext.Save(this); //Returns a BasicType return (T)Activator.CreateInstance(typeof(T), b); } } class DerivedType : BasicType { public DerivedType(BasicType b) { } } public static void Main() { DerivedType d = new DerivedType(); d...

How to create a record type more than one polymorphic variables

types,polymorphism,ocaml,record
type 'a item = { name:string; quantity:'a };; This is a polymorphic type definition taught in Ocaml class. I'm trying extend this type have more than one polymorphic variables in item type like: type 'a item = { name:string; quantity:'a; price:'b };; But, I'm getting an error with unbound value...

I want to Create Car object using Vehicle class ( i.e Vehicle c = new Car() ), and insert it into the list correctly

java,inheritance,polymorphism
I created a Car object using Vehicle class ( i.e Vehicle c = new Car() ), but my problem is how I will insert it into the list then Prompt the user to enter details for this object after the insertion in the list import java.util.ArrayList; import java.util.Scanner; public class...

Using pointers, overridden method not being called

c++,oop,pointers,polymorphism
I am using a vector of pointers to Primitives: vector<Primitive*> primitives; In which I put a pointer to a class derived from Primitive, namely Instance: Shape * s = new Sphere(); PhongMaterial* mat = new PhongMaterial(this, 0.6, 0.15, 0.2, Color(1, 0, 0), 50); Instance* redSphere = new Instance(s, mat); redSphere->scale(1,...

Redefine a constant member variable in inherited class

c++,inheritance,polymorphism
Say I wish to define a member variable in a parent class and set its value in an inherited class. Perhaps these identify functionality available in the class or the nature of the child class. For example: class A { public: inline int getX() { return x; } protected: const...