Search Results

Search found 1494 results on 60 pages for 'prototypal inheritance'.

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

  • Rails: Single Table Inheritance and models subdirectories

    - by Chris
    I have a card-game application which makes use of Single Table Inheritance. I have a class Card, and a database table cards with column type, and a number of subclasses of Card (including class Foo < Card and class Bar < Card, for the sake of argument). As it happens, Foo is a card from the original printing of the game, which Bar is a card from an expansion. In an attempt to rationalise my models, I have created a directory structure like so: app/ + models/ + card.rb + base_game/ + foo.rb + expansion/ + bar.rb And modified environment.rb to contain: Rails::Initializer.run do |config| config.load_paths += Dir["#{RAILS_ROOT}/app/models/**"] end However, when my reads a card from the database, Rails throws the following exception: ActiveRecord::SubclassNotFound (The single-table inheritance mechanism failed to locate the subclass: 'Foo'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Card.inheritance_column to use another column for that information.) Is it possible to make this work, or am I doomed to a flat directory structure?

    Read the article

  • C++ private inheritance and static members/types

    - by WearyMonkey
    I am trying to stop a class from being able to convert its 'this' pointer into a pointer of one of its interfaces. I do this by using private inheritance via a middle proxy class. The problem is that I find private inheritance makes all public static members and types of the base class inaccessible to all classes under the inheriting class in the hierarchy. class Base { public: enum Enum { value }; }; class Middle : private Base { }; class Child : public Middle { public: void Method() { Base::Enum e = Base::value; // doesn't compile BAD! Base* base = this; // doesn't compile GOOD! } }; I've tried this in both VS2008 (the required version) and VS2010, neither work. Can anyone think of a workaround? Or a different approach to stopping the conversion? Also I am curios of the behavior, is it just a side effect of the compiler implementation, or is it by design? If by design, then why? I always thought of private inheritance to mean that nobody knows Middle inherits from Base. However, the exhibited behavior implies private inheritance means a lot more than that, in-fact Child has less access to Base than any namespace not in the class hierarchy!

    Read the article

  • Javascript function using "this = " gives "Invalid left-hand side in assignment"

    - by Brian M. Hunt
    I am trying to get a Javascript object to use the "this" assignments of another objects' constructor, as well as assume all that objects' prototype functions. Here's an example of what I'm attempting to accomplish: /* The base - contains assignments to 'this', and prototype functions */ function ObjX(a,b) { this.$a = a, $b = b; } ObjX.prototype.getB() { return this.$b; } function ObjY(a,b,c) { // here's what I'm thinking should work: this = ObjX(a, b * 12); /* and by 'work' I mean ObjY should have the following properties: * ObjY.$a == a, ObjY.$b == b * 12, * and ObjY.getB() == ObjX.prototype.getB() * ... unfortunately I get the error: * Uncaught ReferenceError: Invalid left-hand side in assignment */ this.$c = c; // just to further distinguish ObjY from ObjX. } I'd be grateful for your thoughts on how to have ObjY subsume ObjX's assignments to 'this' (i.e. not have to repeat all the this.$* = * assignments in ObjY's constructor) and have ObjY assume ObjX.prototype. My first thought is to try the following: function ObjY(a,b,c) { this.prototype = new ObjX(a,b*12); } Ideally I'd like to learn how to do this in a prototypal way (i.e. not have to use any of those 'classic' OOP substitutes like Base2). It may be noteworthy that ObjY will be anonymous (e.g. factory['ObjX'] = function(a,b,c) { this = ObjX(a,b*12); ... }) -- if I've the terminology right. Thank you.

    Read the article

  • structures, inheritance and definition

    - by Meloun
    Hi, i need to help with structures, inheritance and definition. //define struct struct tStruct1{ int a; }; //definition tStruct1 struct1{1}; and inheritance struct tStruct2:tStruct1{ int b; }; How can I define it in declaration line? tStruct2 struct2{ ????? }; One more question, how can i use inheritance for structures defined with typedef struct?

    Read the article

  • Backbone inheritance - deep copying

    - by Ed .
    I've seen this question regarding inheritance in Backbone: Backbone.js view inheritance. Useful but doesn't answer my question. The problem I'm experiencing is this: Say I have a class Panel (model in this example); var Panel = Backbone.Model.extend({ defaults : { name : 'my-panel' } }); And then an AdvancedPanel; var AdvancedPanel = Panel.extend({ defaults : { label : 'Click to edit' } }); The following doesn't work: var advancedPanel = new AdvancedPanel(); alert(advancedPanel.get('name')); // Undefined :( JSFiddle here: http://jsfiddle.net/hWmnb/ I guess I can see that I can achieve this myself through some custom extend function that creates a deep copy of the prototype, but this seems like a common thing that people might want from Backbone inheritance, is there a standard way of doing it?

    Read the article

  • Propel Single Table Inheritance Issue

    - by lo_fye
    I have a table called "talk", which is defined as abstract in my schema.xml file. It generates 4 objects (1 per classkey): Comment, Rating, Review, Checkin It also generates TalkPeer, but I couldn't get it to generate the other 4 peers (CommentPeer, RatingPeer, ReviewPeer, CheckinPeer), so I created them by hand, and made them inherit from TalkPeer.php, which inherits from BaseTalkPeer. I then implemented getOMClass() in each of those peers. The problem is that when I do queries using the 4 peers, they return all 4 types of objects. That is, ReviewPeer will return Visits, Ratings, Comments, AND Reviews. Example: $c = new Criteria(); $c->add(RatingPeer::VALUE, 5, Criteria::GREATER_THAN); $positive_ratings = RatingPeer::doSelect($c); This returns all comments, ratings, reviews, & checkins that have a value 5. ReviewPeer should only return Review objects, and can't figure out how to do this. Do I actually have to go through and change all my criteria to manually specify the classkey? That seems a little pointless, since the Peer name already distinct. I don't want to have to customize each Peer. I should be able to customize JUST the TalkPeer, since they all inherit from it... I just can't figure out how. I tried changing doSelectStmt just in TalkPeer so that it automatically adds the CLASSKEY restriction to the Criteria. It almost works, but I get a: Fatal error: Cannot instantiate abstract class Talk in /models/om/BaseTalkPeer.php on line 503. Line 503 is in BaseTalkPeer::populateObjects(), and is the 3rd line below: $cls = TalkPeer::getOMClass($row, 0); $cls = substr('.'.$cls, strrpos('.'.$cls, '.') + 1); $obj = new $cls(); The docs talked about overriding BaseTalkPeer::populateObject(). I have a feeling that's my problem, but even after reading the source code, I still couldn't figure out how to get it to work. Here is what I tried in TalkPeer::doSelectStmt: public static function doSelectStmt(Criteria $criteria, PropelPDO $con = null) { $keys = array('models.Visit'=>1,'models.Comment'=>2,'models.Rating'=>3,'models.Review'=>4); $class_name = self::getOMClass(); if(isset($keys[$class_name])) { //Talk itself is not a returnable type, so we must check $class_key = $keys[$class_name]; $criteria->add(TalkPeer::CLASS_KEY, $class_key); } return parent::doSelectStmt($criteria, $con = null); } Here is an example of my getOMClass method from ReviewPeer: public static function getOMClass() { return self::CLASSNAME_4; //aka 'talk.Review'; } Here is the relevant bit of my schema: <table name="talk" idMethod="native" abstract="true"> <column name="talk_pk" type="INTEGER" required="true" autoIncrement="true" primaryKey="true" /> <column name="class_key" type="INTEGER" required="true" default="" inheritance="single"> <inheritance key="1" class="Visit" extends="models.Talk" /> <inheritance key="2" class="Comment" extends="models.Talk" /> <inheritance key="3" class="Rating" extends="models.Talk" /> <inheritance key="4" class="Review" extends="models.Rating" /> </column> </table> P.S. - No, I can't upgrade from 1.3 to 1.4. There's just too much code that would need to be re-tested

    Read the article

  • How to refactor my design, if it seems to require multiple inheritance?

    - by Omega
    Recently I made a question about Java classes implementing methods from two sources (kinda like multiple inheritance). However, it was pointed out that this sort of need may be a sign of a design flaw. Hence, it is probably better to address my current design rather than trying to simulate multiple inheritance. Before tackling the actual problem, some background info about a particular mechanic in this framework: It is a simple game development framework. Several components allocate some memory (like pixel data), and it is necessary to get rid of it as soon as you don't need it. Sprites are an example of this. Anyway, I decided to implement something ala Manual-Reference-Counting from Objective-C. Certain classes, like Sprites, contain an internal counter, which is increased when you call retain(), and decreased on release(). Thus the Resource abstract class was created. Any subclass of this will obtain the retain() and release() implementations for free. When its count hits 0 (nobody is using this class), it will call the destroy() method. The subclass needs only to implement destroy(). This is because I don't want to rely on the Garbage Collector to get rid of unused pixel data. Game objects are all subclasses of the Node class - which is the main construction block, as it provides info such as position, size, rotation, etc. See, two classes are used often in my game. Sprites and Labels. Ah... but wait. Sprites contain pixel data, remember? And as such, they need to extend Resource. But this, of course, can't be done. Sprites ARE nodes, hence they must subclass Node. But heck, they are resources too. Why not making Resource an interface? Because I'd have to re-implement retain() and release(). I am avoiding this in virtue of not writing the same code over and over (remember that there are multiple classes that need this memory-management system). Why not composition? Because I'd still have to implement methods in Sprite (and similar classes) that essentially call the methods of Resource. I'd still be writing the same code over and over! What is your advice in this situation, then?

    Read the article

  • What is the exact problem with multiple inheritance?

    - by Totophil
    I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java and C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. What’s the matter with the multiple inheritance? Are there any concrete samples?

    Read the article

  • Does Java not support multiple inheritance?

    - by user1720616
    Lets us take instances of two classes public abstract class Shapes { public abstract void draw(Graphics g); } public class Rectangle extends Shapes { public void draw(Graphics g) { //implementation of the method } } here the class Rectangle has extended class Shapes and implicitly it extends class Object.I know no other extension is possible but cant we call inheriting classes Shapes and Object multiple inheritance?(Since inheriting two classes is multiple inheritance from one perspective)

    Read the article

  • How should I plan the inheritance structure for my game?

    - by Eric Thoma
    I am trying to write a platform shooter in C++ with a really good class structure for robustness. The game itself is secondary; it is the learning process of writing it that is primary. I am implementing an inheritance tree for all of the objects in my game, but I find myself unsure on some decisions. One specific issue that it bugging me is this: I have an Actor that is simply defined as anything in the game world. Under Actor is Character. Both of these classes are abstract. Under Character is the Philosopher, who is the main character that the user commands. Also under Character is NPC, which uses an AI module with stock routines for friendly, enemy and (maybe) neutral alignments. So under NPC I want to have three subclasses: FriendlyNPC, EnemyNPC and NeutralNPC. These classes are not abstract, and will often be subclassed in order to make different types of NPC's, like Engineer, Scientist and the most evil Programmer. Still, if I want to implement a generic NPC named Kevin, it would nice to be able to put him in without making a new class for him. I could just instantiate a FriendlyNPC and pass some values for the AI machine and for the dialogue; that would be ideal. But what if Kevin is the one benevolent Programmer in the whole world? Now we must make a class for him (but what should it be called?). Now we have a character that should inherit from Programmer (as Kevin has all the same abilities but just uses the friendly AI functions) but also should inherit from FriendlyNPC. Programmer and FriendlyNPC branched away from each other on the inheritance tree, so inheriting from both of them would have conflicts, because some of the same functions have been implemented in different ways on the two of them. 1) Is there a better way to order these classes to avoid these conflicts? Having three subclasses; Friendly, Enemy and Neutral; from each type of NPC; Engineer, Scientist, and Programmer; would amount to a huge number of classes. I would share specific implementation details, but I am writing the game slowly, piece by piece, and so I haven't implemented past Character yet. 2) Is there a place where I can learn these programming paradigms? I am already trying to take advantage of some good design patterns, like MVC architecture and Mediator objects. The whole point of this project is to write something in good style. It is difficult to tell what should become a subclass and what should become a state (i.e. Friendly boolean v. Friendly class). Having many states slows down code with if statements and makes classes long and unwieldy. On the other hand, having a class for everything isn't practical. 3) Are there good rules of thumb or resources to learn more about this? 4) Finally, where does templating come in to this? How should I coordinate templates into my class structure? I have never actually taken advantage of templating honestly, but I hear that it increases modularity, which means good code.

    Read the article

  • WCF data services (OData), query with inheritance limitation?

    - by Mathieu Hétu
    Project: WCF Data service using internally EF4 CTP5 Code-First approach. I configured entities with inheritance (TPH). See previous question on this topic: Previous question about multiple entities- same table The mapping works well, and unit test over EF4 confirms that queries runs smoothly. My entities looks like this: ContactBase (abstract) Customer (inherits from ContactBase), this entity has also several Navigation properties toward other entities Resource (inherits from ContactBase) I have configured a discriminator, so both Customer and Resource map to the same table. Again, everythings works fine on the Ef4 point of view (unit tests all greens!) However, when exposing this DBContext over WCF Data services, I get: - CustomerBases sets exposed (Customers and Resources sets seems hidden, is it by design?) - When I query over Odata on Customers, I get this error: Navigation Properties are not supported on derived entity types. Entity Set 'ContactBases' has a instance of type 'CodeFirstNamespace.Customer', which is an derived entity type and has navigation properties. Please remove all the navigation properties from type 'CodeFirstNamespace.Customer'. Stacktrace: at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content, EpmSourcePathSegment currentSourceRoot) at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, ResourceType expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target) at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__b.MoveNext() at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer) at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved) at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved) at System.Data.Services.ResponseBodyWriter.Write(Stream stream) Seems like a limitation of WCF Data services... is it? Not much documentation can be found on the web about WCF Data services (OData) and inheritance specifications. How can I overpass this exception? I need these navigation properties on derived entities, and inheritance seems the only way to provide mapping of 2 entites on the same table with Ef4 CTP5... Any thoughts?

    Read the article

  • Question about Virtual Inheritance hierarchy

    - by Summer_More_More_Tea
    Hi there: I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class? By the way, why the output of the following code is: sizeof(A): 8 sizeof(B): 20 sizeof(C): 20 sizeof(C): 36 Code: #include <iostream> using namespace std; class A{ char k[ 3 ]; public: virtual void a(){}; }; class B : public virtual A{ char j[ 3 ]; public: virtual void b(){}; }; class C : public virtual B{ char i[ 3 ]; public: virtual void c(){}; }; class D : public B, public C{ char h[ 3 ]; public: virtual void d(){}; }; int main( int argc, char *argv[] ){ cout << "sizeof(A): " << sizeof( A ) << endl; cout << "sizeof(B): " << sizeof( B ) << endl; cout << "sizeof(C): " << sizeof( C ) << endl; cout << "sizeof(D): " << sizeof( D ) << endl; return 0; } Thanks in advance. Kind regards.

    Read the article

  • symfony + doctrine + inheritance, how to make them work?

    - by imac
    I am beginning to work with Symfony, I've found some documentation about inheritance. But also found this discouraging article, which make me doubt if Doctrine handles inheritance any good at all... Has anyone find a smart solution for inheritance in Symfony+Doctrine? As an example, I have already structured the database something like this: CREATE TABLE `poster` ( `poster_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, PRIMARY KEY (`poster_id`), UNIQUE KEY `id` (`poster_id`), ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `real_name` varchar(50) DEFAULT NULL, PRIMARY KEY (`user_id`), UNIQUE KEY `user_id` (`user_id`), CONSTRAINT `user_fk` FOREIGN KEY (`user_id`) REFERENCES `poster` (`poster_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; From that, Doctrine generated this "schema.yml": Poster: connection: doctrine tableName: poster columns: poster_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: true user_name: type: string(50) fixed: false unsigned: false primary: false notnull: true autoincrement: false relations: Post: local: poster_id foreign: poster_id type: many User: local: poster_id foreign: user_id type: many Version: local: poster_id foreign: poster_id type: many User: connection: doctrine tableName: user columns: user_id: type: integer(4) fixed: false unsigned: false primary: true autoincrement: false real_name: type: string(50) fixed: false unsigned: false primary: false notnull: false autoincrement: false relations: Poster: local: user_id foreign: poster_id type: one User creation for this structure with Doctrine auto-generated forms does not work. Any clue will be appreciated.

    Read the article

  • Entity Framework inheritance: TPT, TPH or none?

    - by silverfighter
    Hi, I am currently reading about the possibility about using inheritance with Entity Framework. Sometimes I use a approch to type data records and I am not sure if I would use TPT or TPH or none... For example... I have a ecommerce shop which adds shipping, billing, and delivery address I have a address table: RecordID AddressTypeID Street ZipCode City Country and a table AddressType RecordID AddressTypeDescription The table design differs to the gerneral design when people show off TPT or TPH... Does it make sense to think about inheritance an when having a approach like this.. I hope it makes sense... Thanks for any help...

    Read the article

  • Inheritance in Java

    - by Mandar
    Hello, recently I went through the inheritance concept. As we all know, in inheritance, superclass objects are created/initialized prior to subclass objects. So if we create an object of subclass, it will contain all the superclass information. But I got stuck at one point. Do the superclass and the subclass methods are present on separate call-stack? If it is so, is there any specific reason for same? If it is not so, why they don't appear on same call-stack? E.g. // Superclass class A { void play1( ) { // .... } } // Subclass class B extends A { void play2( ) { //..... } } Then does the above 2 methods i.e play1( ) and play2( ) appear on separate call stack? Thanks.

    Read the article

  • JPA Inheritance and Relations - Clarification question

    - by Michael
    Here the scenario: I have a unidirectional 1:N Relation from Person Entity to Address Entity. And a bidirectional 1:N Relation from User Entity to Vehicle Entity. Here is the Address class: @Entity public class Address implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) privat Long int ... The Vehicles Class: @Entity public class Vehicle implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne private User owner; ... @PreRemove protected void preRemove() { //this.owner.removeVehicle(this); } public Vehicle(User owner) { this.owner = owner; ... The Person Class: @Entity @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name="PERSON_TYP") public class Person implements Serializable { @Id protected String username; @OneToMany(cascade = CascadeType.ALL, orphanRemoval=true) @JoinTable(name = "USER_ADDRESS", joinColumns = @JoinColumn(name = "USERNAME"), inverseJoinColumns = @JoinColumn(name = "ADDRESS_ID")) protected List<Address> addresses; ... @PreRemove protected void prePersonRemove(){ this.addresses = null; } ... The User Class which is inherited from the Person class: @Entity @Table(name = "Users") @DiscriminatorValue("USER") public class User extends Person { @OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) private List<Vehicle> vehicles; ... When I try to delete a User who has an address I have to use orphanremoval=true on the corresponding relation (see above) and the preRemove function where the address List is set to null. Otherwise (no orphanremoval and adress list not set to null) a foreign key contraint fails. When i try to delete a user who has an vehicle a concurrent Acces Exception is thrown when do not uncomment the "this.owner.removeVehicle(this);" in the preRemove Function of the vehicle. The thing i do not understand is that before i used this inheritance there was only a User class which had all relations: @Entity @Table(name = "Users") public class User implements Serializable { @Id protected String username; @OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) private List<Vehicle> vehicles; @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "USER_ADDRESS", joinColumns = @JoinColumn(name = "USERNAME") inverseJoinColumns = @JoinColumn(name = "ADDRESS_ID")) ptivate List<Address> addresses; ... No orphanremoval, and the vehicle class has used the uncommented statement above in its preRemove function. And - I could delte a user who has an address and i could delte a user who has a vehicle. So why doesn't everything work without changes when i use inheritance? I use JPA 2.0, EclipseLink 2.0.2, MySQL 5.1.x and Netbeans 6.8

    Read the article

  • Inheritance or identifier

    - by Lina
    Hi! Does anyone here have opinions about when to user inheritance and when to use an identifier instead? Inheritance example: class Animal { public int Name { get; set; } } class Dog : Animal {} class Cat : Animal {} Identifier example: class Animal { public int Name { get; set; } public AnimalType { get; set; } } In what situations should i prefer which solution and what are the pros and cons for them? /Lina

    Read the article

  • Linq to SQL inheritance and Table per Class - approach needed for multiple roles

    - by Ash Machine
    I am using L2S and an inheritance model for mapping Persons against certain roles. Guy Burstein's excellent blog post explains how to accomplish this: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/01/linq-to-sql-inheritance.aspx However, I have a specific case where a Person has multiple roles. For example 'Jane Doe' is a Contact and a Programmer. In this model, she would need two rows in the People table, one as Contact (PersonType = 1) and one as Programmer (PersonType = 3). If she changes her last name, and that update happens in her role as Contact, I would need to change all instances of 'Jane Doe' to reflect the name change everywhere. What sort of best approach (improved data structure) could be used to change last name within all roles? Finally, I am hoping to avoid overriding each general form update events to include all instances, but that may be the only way. Any suggestions or approaches appreciated.

    Read the article

  • Table per subclass inheritance relationship: How to query against the Parent class without loading a

    - by Arthur Ronald F D Garcia
    Suppose a Table per subclass inheritance relationship which can be described bellow (From wikibooks.org - see here) Notice Parent class is not abstract @Entity @Inheritance(strategy=InheritanceType.JOINED) public class Project { @Id private long id; // Other properties } @Entity @Table(name="LARGEPROJECT") public class LargeProject extends Project { private BigDecimal budget; } @Entity @Table(name="SMALLPROJECT") public class SmallProject extends Project { } I have a scenario where i just need to retrieve the Parent class. Because of performance issues, What should i do to run a HQL query in order to retrieve the Parent class and just the Parent class without loading any subclass ???

    Read the article

  • Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?

    - by Brettetete
    Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture. So I want to do create an architecture for NPCs in a video-game. It is a Realtime Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack(). Examples: Worker can Build() and Farm() Warrior can Attack() Citizen can Build(), Farm() and Attack() Fisherman can Farm() and Attack() I hope everything is clear so far. So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect. What would be a good programmatic architecture for my different kinds of NPCs? Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle. So I can have methods like WalkTo(x,y) in my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack()) Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..). Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild, .. I think it is clear what I want to express. But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality. I do use C# as programming language. So multiple inheritance isn't an opinion here. Means: Having extra base classes like Fisherman : Farmer, Attacker won't work.

    Read the article

  • C++ Exceptions and Inheritance from std::exception

    - by fbrereto
    Given this sample code: #include <iostream> #include <stdexcept> class my_exception_t : std::exception { public: explicit my_exception_t() { } virtual const char* what() const throw() { return "Hello, world!"; } }; int main() { try { throw my_exception_t(); } catch (const std::exception& error) { std::cerr << "Exception: " << error.what() << std::endl; } catch (...) { std::cerr << "Exception: unknown" << std::endl; } return 0; } I get the following output: Exception: unknown Yet simply making the inheritance of my_exception_t from std::exception public, I get the following output: Exception: Hello, world! Could someone please explain to me why the type of inheritance matters in this case? Bonus points for a reference in the standard.

    Read the article

  • How does virtual inheritance solve the diamond problem?

    - by cambr
    class A { public: void eat(){ cout<<"A";} }; class B: virtual public A { public: void eat(){ cout<<"B";} }; class C: virtual public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main(){ A *a = new D(); a->eat(); } I understand the diamond problem, and above piece of code does not have that problem. How exatly does virtual inheritance solve the problem? What I understand: When I say A *a = new D();, the compiler wants to know if an object of type D can be assigned to a pointer of type A, but it has two paths that it can follow, but cannot decide by itself. So, how does virtual inheritance resolve the issue (help compiler take the decision)?

    Read the article

  • Active Record two belongs_to calls or single table inheritance

    - by ethyreal
    In linking a sports event to two teams, at first this seemed to make sense: events - id:integer - integer:home_team_id - integer:away_team_id teams - integer:id - string:name However I am troubled by how I would link that up in the active record model: class Event belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id" belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id" end Is that the best solution? In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. If I did go with single table inheritance I wouldn't want each team to belong_to an event so would this work? # app/models/event.rb class Event < ActiveRecord::Base belongs_to :home_team belongs_to :away_team end # app/models/team.rb class Team < ActiveRecord::Base has_many :teams end # app/models/home_team.rb class HomeTeam < Team end # app/models/away_team.rb class AwayTeam < Team end I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event. event_teams - integer:event_id - integer:team_id - boolean:is_home Is there a cleaner more semantic way for making these associations in active record? or is one of these solutions the best choice? Thanks

    Read the article

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