Search Results

Search found 256 results on 11 pages for 'superclass'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • Just how much do I want to make virtual?

    - by Alex
    I am writing an abstract superclass where literally every method is going to be overridden. There is some default functionality I could implement, but most of the time it's enough to leave the implementation to the subclass writer. Since just about every method is going to be overwritten, how much should I make virtual and how much should I just leave as regular methods? In the current incarnation, everything is virtual, but I still haven't let this loose to anyone to use, so the design is flexible. What advantages/disadvantages are there to virtual functions? Links to good reading material about this would be appreciated.

    Read the article

  • Subtyping and assignment in Java

    - by Danrex
    Arghh I just know people are going to hate me for asking this... I was just playing around with inheritance and I noticed you can instantiate a subclass object in one of two ways when you write code. So then I wondered if there is any functional difference between these two methods. So in the code below, does this produce the exact same result...a MountainBike object, or is there some difference I should know about? Bicycle is the superclass for this example. If I do Bicycle bike or MountainBike bike I am effectively making a MountainBike due to new MountainBike()? So basically the difference is just semantics at this point? Bicycle bike = new MountainBike(); MountainBike bike = new MountainBike();

    Read the article

  • What is a good design model for my new class?

    - by user66662
    I am a beginning programmer who, after trying to manage over 2000 lines of procedural php code, now has discovered the value of OOP. I have read a few books to get me up to speed on the beginning theory, but would like some advice on practical application. So,for example, let's say there are two types of content objects - an ad and a calendar event. what my application does is scan different websites (a predefined list), and, when it finds an ad or an event, it extracts the data and saves it to a database. All of my objects will share a $title and $description. However, the Ad object will have a $price and the Event object will have $startDate. Should I have two separate classes, one for each object? Should I have a 'superclass' with the $title and $description with two other Ad and Event classes with their own properties? The latter is at least the direction I am on now. My second question about this design is how to handle the logic that extracts the data for $title, $description, $price, and $date. For each website in my predefined list, there is a specific regex that returns the desired value for each property. Currently, I have an extremely large switch statement in my constructor which determines what website I am own, sets the regex variables accordingly, and continues on. Not only that, but now I have to repeat the logic to determine what site I am on in the constructor of each class. This doesn't feel right. Should I create another class Algorithms and store the logic there for each site? Should the functions of to handle that logic be in this class? or specific to the classes whos properties they set? I want to take into account in my design two things: 1) I will add different content objects in the future that share $title and $description, but will have their own properties, so, I want to be able to easily grow these as needed. 2) I will add more websites constantly (each with their own algorithms for data extraction) so I would like to plan efficienty managing and working with these now. I thought about extending the Ad or Event class with 'websiteX' class and store its functions there. But, this didn't feel right either as now I have to manage 100s of little website specific class files. Note, I didn't know if this was the correct site or stackoverflow was the better choice. If so, let me know and I'll post there.

    Read the article

  • Android Custom View Constructor

    - by Mitch
    I'm learning about using Custom Views from the following: http://developer.android.com/guide/topics/ui/custom-components.html#modifying The description says: Class Initialization As always, the super is called first. Furthermore, this is not a default constructor, but a parameterized one. The EditText is created with these parameters when it is inflated from an XML layout file, thus, our constructor needs to both take them and pass them to the superclass constructor as well. Is there a better description? I've been trying to figure out what the constructor(s) should look like and I've come up with 4 possible choices (see example at end of post). I'm not sure what these 4 choices do (or don't do), why I should implement them, or what the parameters mean. Is there a description of these? Thanks. Mitch public MyCustomView() { super(); } public MyCustomView(Context context) { super(context); } public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); } public MyCustomView(Context context, AttributeSet attrs, Map params) { super(context, attrs, params); }

    Read the article

  • Caching a column in a polymorphic relationship

    - by Brendon Muir
    I have content management system application that uses a polymorphic tree table as the core of its arrangement. I've come into a problem where once the tree grows quite large, and because we have quite a few different modules (about 25), just doing :include = :instance doesn't cut the mustard. Instance is the name of our polymorphic relationship. The funny part is that in most cases when I want a large list of these items, all I really want is their name from the associated table (for the purposes of an index bar for example), all the rest is in the central table. So I thought that I should probably implement some sort of column cache for the name in the central table. (Like a counter cache that rails already does). I was just wondering if a plugin exists to manage this already? If not, I was just going to add a 'name' column to the central table and because all the polymorphic models inherit off a superclass, just add a callback that pushes the name across to the central table whenever the item is created or updated. I'd then just do a big migration to populate it in the first place? Any flaws to that design? I suppose to be more flexible the column could be some kind of serialised cache where I could store other things later on if need be? Gah! :D

    Read the article

  • Help to understand the issue with protected method

    - by zeroed
    I'm reading Sybex Complete Java 2 Certification Study Guide April 2005 (ISBN0782144195). This book is for java developers who wants to pass java certification. After a chapter about access modifiers (along with other modifiers) I found the following question (#17): True or false: If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y. This question confused me a little. As far as I know you can call protected method on any variable of the same class (or subclasses). You cannot call it on variables, that higher in the hierarchy than you (e.g. interfaces that you implement). For example, you cannot clone any object just because you inherit it. But the questions says nothing about variable type, only about instance type. I was confused a little and answered "true". The answer in the book is False. An object that inherits a protected method from a superclass in a different package may call that method on itself but not on other instances of the same class. There is nothing here about variable type, only about instance type. This is very strange, I do not understand it. Can anybody explain what is going on here?

    Read the article

  • Accessing a class's containing namespace from within a module

    - by SFEley
    I'm working on a module that, among other things, will add some generic 'finder' type functionality to the class you mix it into. The problem: for reasons of convenience and aesthetics, I want to include some functionality outside the class, in the same scope as the class itself. For example: class User include MyMagicMixin end # Should automagically enable: User.name('Bob') # Returns first user named Bob Users.name('Bob') # Returns ALL users named Bob User(5) # Returns the user with an ID of 5 Users # Returns all users I can do the functionality within these methods, no problem. And case 1 (User.name('Bob')) is easy. Cases 2–4, however, require being able to create new classes and methods outside User. The Module.included method gives me access to the class, but not to its containing scope. There is no simple "parent" type method that I can see on Class nor Module. (For namespace, I mean, not superclass nor nested modules.) The best way I can think to do this is with some string parsing on the class's #name to break out its namespace, and then turn the string back into a constant. But that seems clumsy, and given that this is Ruby, I feel like there should be a more elegant way. Does anyone have ideas? Or am I just being too clever for my own good?

    Read the article

  • How do I set YUI2 paginator to select a page other than the first page?

    - by Jeremy Weathers
    I have a YUI DataTable (YUI 2.8.0r4) with AJAX pagination. Each row in the table links to a details/editing page and I want to link from that details page back to the list page that includes the record from the details page. So I have to a) offset the AJAX data correctly and b) tell YAHOO.widget.Paginator which page to select. According to my reading of the YUI API docs, I have to pass in the initialPage configuration option. I've attempted this, but it doesn't take (the data from AJAX is correctly offset, but the paginator thinks I'm on page 1, so clicking "next" takes me from e.g. page 6 to page 2. What am I not doing (or doing wrong)? Here's my DataTable building code: (function() { var columns = [ {key: "retailer", label: "Retailer", sortable: false, width: 80}, {key: "publisher", label: "Publisher", sortable: false, width: 300}, {key: "description", label: "Description", sortable: false, width: 300} ]; var source = new YAHOO.util.DataSource("/sales_data.json?"); source.responseType = YAHOO.util.DataSource.TYPE_JSON; source.responseSchema = { resultsList: "records", fields: [ {key: "url"}, {key: "retailer"}, {key: "publisher"}, {key: "description"} ], metaFields: { totalRecords: "totalRecords" } }; var LoadingDT = function(div, cols, src, opts) { LoadingDT.superclass.constructor.call( this, div, cols, src, opts); // hide the message tbody this._elMsgTbody.style.display = "none"; }; YAHOO.extend(LoadingDT, YAHOO.widget.DataTable, { showTableMessage: function(msg) { $('sales_table_overlay').clonePosition($('sales_table').down('table')). show(); }, hideTableMessage: function() { $('sales_table_overlay').hide(); } }); var table = new LoadingDT("sales_table", columns, source, { initialRequest: "startIndex=125&results=25", dynamicData: true, paginator: new YAHOO.widget.Paginator({rowsPerPage: 25, initialPage: 6}) }); table.handleDataReturnPayload = function(oRequest, oResponse, oPayload) { oPayload.totalRecords = oResponse.meta.totalRecords; return oPayload; }; })();

    Read the article

  • SubViewTwoController undeclared (first use in this function) (obj-c)

    - by benny
    Ahoy hoy everyone :) Here is a list of links. You will need it when reading the post. I am a newbie to Objective-C and try to learn it for iPhone-App-Development. I used the tutorial linked in the link list to create a standard app with a simple basic Navigation. This app contains a "RootView" that is displayed at startup. The startup screen itself contains three elements wich all link to SubViewOne. I have got it to work this far. So what i want to change is to make the second element link to SubViewTwo. When i "Build and Go" it, i get the following errors: RootViewController.m: SubViewTwoController *subViewTwoController = [[SubViewTwoController alloc] init]; // SubViewTwoController undeclared (first use in this function) and in SubViewTwoController.m [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview no superclass declared in @interface for ´SubViewTwoController´ and the same thing after - (void)dealloc { [super dealloc]; I think you will also need the header files, so here they are! RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController : UITableViewController { IBOutlet NSMutableArray *views; } @property (nonatomic, retain) IBOutlet NSMutableArray *views; @end SubViewOneController.h #import <UIKit/UIKit.h> @interface SubViewOneController : UIViewController { IBOutlet UILabel *label; IBOutlet UIButton *button; } @property (retain,nonatomic) IBOutlet UILabel *label; @property (retain,nonatomic) IBOutlet UIButton *button; - (IBAction) OnButtonClick:(id) sender; @end and SubViewTwoController.h #import <UIKit/UIKit.h> @interface SubViewTwo : UIViewController { IBOutlet NSMutableArray *views; } @end I would be really great if you would leave your ideas with a short explanation. Thanks a lot in advance! benny

    Read the article

  • javascript: what does this syntax means?

    - by user1067138
    it is like this: (function () { //codes here })(); here is an example: (function () { var D = TED.EditorCore, E = TED.extend, A = TED.EditorInstanceManager, B = TED.augmentObject; window.TED["SimpleEditor"] = C; function C(F) { C.superclass.call(this, F) } C.defaultConfig = { height: "100px", width: "400px", //blablabla... flashNumLimit: 10, didaDelay: 300, imageWidthLimit: 570 }; E(C, D, { getContentLength: function () { return Math.ceil(this.filteHTML(this.editArea.innerHTML, ["img", "br"]).replace(/<img[^>]*>/gi, "mm").replace(/<br[^>]*>/gi, "m").replace(/&nbsp;/gi, "m").replace(/[^\x00-\xff]/g, "mm").length / 2) }, filteEditHTML: function () { return html = this.editArea.innerHTML.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(new RegExp("<\\/?(?:br[^>]*)>", "gi"), "[$1]").replace(new RegExp('<span([^>]*class="?at"?[^>]*)>', "gi"), "[span$1]").replace(new RegExp('<img([^>]*class="?(?:' + this.config.emptyClassName + "|" + this.config.smileyClassName + ')"?[^>]*)>', "gi"), "[img$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:br|img|span)[^\\]]*)\\]", "gi"), "<$1>") }, filteSubmitHTML: function () { this.reLayout(); var G = this.editArea.innerHTML.replace(/_moz_dirty=""/gi, "").replace(/\[/g, "[[-").replace(/\]/g, "-]]").replace(new RegExp("<(/?(?:" + this.submitValidHTML.join("|") + ")[^>]*)>", "gi"), "[$1]").replace(new RegExp('<img([^>]*class="?(?:' + this.config.imageClassName + "|" + this.config.smileyClassName + "|" + this.config.flashClassName + "|" + this.config.musicClassName + ')"?[^>]*)>', "gi"), "[img$1]").replace(/<[^>]*>/g, "").replace(/\[\[\-/g, "[").replace(/\-\]\]/g, "]").replace(new RegExp("\\[(/?(?:" + this.submitValidHTML.join("|") + "|img)[^\\]]*)\\]", "gi"), "<$1>"); var F = document.createElement("div"); F.innerHTML = G; this.parseURL(F); return F.innerHTML } }); B(C, A) })(); what exactly does (funtion (){})(); do?

    Read the article

  • iPhone View Switching basics.

    - by Daniel Granger
    I am just trying to get my head around simple view switching for the iPhone and have created a simple app to try and help me understand it. I have included the code from my root controller used to switch the views. My app has a single toolbar with three buttons on it each linking to one view. Here is my code to do this but I think there most be a more efficient way to achieve this? Is there a way to find out / remove the current displayed view instead of having to do the if statements to see if either has a superclass? I know I could use a tab bar to create a similar effect but I am just using this method to help me practice a few of the techniques. -(IBAction)switchToDataInput:(id)sender{ if (self.dataInputVC.view.superview == nil) { if (dataInputVC == nil) { dataInputVC = [[DataInputViewController alloc] initWithNibName:@"DataInput" bundle:nil]; } if (self.UIElementsVC.view.superview != nil) { [UIElementsVC.view removeFromSuperview]; } else if (self.totalsVC.view.superview != nil) { [totalsVC.view removeFromSuperview]; } [self.view insertSubview:dataInputVC.view atIndex:0]; } } -(IBAction)switchToUIElements:(id)sender{ if (self.UIElementsVC.view.superview == nil) { if (UIElementsVC == nil) { UIElementsVC = [[UIElementsViewController alloc] initWithNibName:@"UIElements" bundle:nil]; } if (self.dataInputVC.view.superview != nil) { [dataInputVC.view removeFromSuperview]; } else if (self.totalsVC.view.superview != nil) { [totalsVC.view removeFromSuperview]; } [self.view insertSubview:UIElementsVC.view atIndex:0]; } } -(IBAction)switchToTotals:(id)sender{ if (self.totalsVC.view.superview == nil) { if (totalsVC == nil) { totalsVC = [[TotalsViewController alloc] initWithNibName:@"Totals" bundle:nil]; } if (self.dataInputVC.view.superview != nil) { [dataInputVC.view removeFromSuperview]; } else if (self.UIElementsVC.view.superview != nil) { [UIElementsVC.view removeFromSuperview]; } [self.view insertSubview:totalsVC.view atIndex:0]; } }

    Read the article

  • Spring-MVC Problem using @Controller on controller implementing an interface

    - by layne
    I'm using spring 2.5 and annotations to configure my spring-mvc web context. Unfortunately, I am unable to get the following to work. I'm not sure if this is a bug (seems like it) or if there is a basic misunderstanding on how the annotations and interface implementation subclassing works. For example, @Controller @RequestMapping("url-mapping-here") public class Foo { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } works fine. When the context starts up, the urls this handler deals with are discovered, and everything works great. This however does not: @Controller @RequestMapping("url-mapping-here") public class Foo implements Bar { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } When I try to pull up the url, I get the following nasty stack trace: javax.servlet.ServletException: No adapter for handler [com.shaneleopard.web.controller.RegistrationController@e973e3]: Does your handler implement a supported interface like Controller? org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1091) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:874) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501) javax.servlet.http.HttpServlet.service(HttpServlet.java:627) However, if I change Bar to be an abstract superclass and have Foo extend it, then it works again. @Controller @RequestMapping("url-mapping-here") public class Foo extends Bar { @RequestMapping(method=RequestMethod.GET) public void showForm() { ... } @RequestMapping(method=RequestMethod.POST) public String processForm() { ... } } This seems like a bug. The @Controller annotation should be sufficient to mark this as a controller, and I should be able to implement one or more interfaces in my controller without having to do anything else. Any ideas?

    Read the article

  • Is a "factory" method the right pattern?

    - by jdt141
    Hey all - So I'm working to improve an existing implementation. I have a number of polymorphic classes that are all composed into a higher level container class. The problem I'm dealing with at the moment is that the higher level container class, well, sucks. It looks something like this, which I really don't have a problem with (as the polymorphic classes in the container should be public). My real issue is the constructor... /* * class1 and class 2 derive from the same superclass */ class Container { public: boost::shared_ptr<ComposedClass1> class1; boost::shared_ptr<ComposedClass2> class2; private: ... } /* * Constructor - builds the objects that we need in this container. */ Container::Container(some params) { class1.reset(new ComposedClass1(...)); class2.reset(new ComposedClass2(...)); } What I really need is to make this container class more re-usable. By hard-coding up the member objects and instantiating them, it basically isn't and can only be used once. A factory is one way to build what I need (potentially by supplying a list of objects and their specific types to be created?) Other ways to get around this problem? Seems like someone should have solved it before... Thanks!

    Read the article

  • Django generic relation field reports that all() is getting unexpected keyword argument when no args

    - by Joshua
    I have a model which can be attached to to other models. class Attachable(models.Model): content_type = models.ForeignKey(ContentType) object_pk = models.TextField() content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") class Meta: abstract = True class Flag(Attachable): user = models.ForeignKey(User) flag = models.SlugField() timestamp = models.DateTimeField() I'm creating a generic relationship to this model in another model. flags = generic.GenericRelation(Flag) I try to get objects from this generic relation like so: self.flags.all() This results in the following exception: >>> obj.flags.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all return self.get_query_set() File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set return superclass.get_query_set(self).filter(**query) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q can_reuse=used_aliases) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter negate=negate, process_extras=process_extras) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins "Choices are: %s" % (name, ", ".join(names))) FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user >>> obj.flags.all(object_pk=obj.pk) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: all() got an unexpected keyword argument 'object_pk' What have I done wrong?

    Read the article

  • Display subclass data in XCode Expression window

    - by Nick VanderPyle
    I'm debugging an iPhone application I've written using XCode 3.2 and I cannot view the relevant public properties of an object I pull from Core Data. When I watch the object in the Expressions window it only displays the data from the base NSManagedObject. I'd like to see the properties that are on the subclass, not the superclass. If it helps, here's some of the code I'm using. Settings is a subclass of NSManagedObject. I created it using XCode's built-in modeler. Declared like: @interface Settings : NSManagedObject { } @property (nonatomic, retain) NSNumber * hasNews; @property (nonatomic, retain) NSString * logoUrl; @property (nonatomic, retain) NSNumber * hasPaymentGateway; @property (nonatomic, retain) NSString * customerCode; ... In the interface of my controller I have: Settings *settings; I populate settings with: settings = (Settings *)[NSEntityDescription insertNewObjectForEntityForName:@"Settings" inManagedObjectContext:UIAppManagedObjectContext()]; I then set the properties like: settings.hasNews = [NSNumber numberWithBool:TRUE]; I've tried casting settings as (Settings *) in the Expression window but that doesn't help. All I see are the properties to NSManagedObject. I'm using NSLog but would rather not.

    Read the article

  • Suggest the way to design several classes

    - by Oleg Tarasenko
    Hi, I'm building simple application on as3. Kind of starship game. What I want to do is to create several different star ships. Each one should have different images (different look), different sets of animation (e.g. when it's flying, burning, damaged), different kind of weapon and also different controllers (e.g. one can be managed by user, another one by computer, and I want to be able to reuse same ships for AI controller as well as for users controls). Each ship is created in the following way: Create entity Add spatial Add renderers Add other components.... ...... n. init the ship So what I am trying to do: 1) Create StarShip superclass, to store HP (as every ship has it), store spatial (same reason) 2) Create inherited class for any other ship... (It will contain renderer - (responsible for display part), weapon, set of animations), etc What do you think about such way of composition? Maybe it's better to place everything in super class, and then just create instances using long, long, long constructors like: StarShip(hp:HP, animations:DICT, weapon:Weapon, ....) Need advice

    Read the article

  • Cyclic Reference - protocols and subclasses

    - by blindJesse
    I'm getting some cyclic reference (I think) problems between a few classes that require imported headers due to either subclassing or protocol definitions. I can explain why things are set up this way but I'm not sure it's essential. Basically these classes are managing reciprocal to-many data relationships. The layout is this: Class A imports Class B because it's a delegate of Class B and needs its protocol definition. Class B imports Class C because it's a subclass of Class C. Class C imports Class A because it's a delegate of Class A and needs its protocol definition. Here's some sample code that illustrates the problem. The errors I'm getting are as follows: In Class A - "Can't find protocol definition for Class_B_Delegate". In Class B - "Can't find interface declaration for Class C - superclass of Class B." In Class C - "Can't find protocol definition for Class_A_Delegate". Class A header: #import <Foundation/Foundation.h> #import "Class_B.h" @protocol Class_A_Delegate @end @interface Class_A : NSObject <Class_B_Delegate> { } @end Class B header: #import <Foundation/Foundation.h> #import "Class_C.h" @protocol Class_B_Delegate <NSObject> @end @interface Class_B : Class_C { } @end Class C Header: #import <Foundation/Foundation.h> #import "Class_A.h" @interface Class_C : NSObject <Class_A_Delegate> { } @end

    Read the article

  • PHP + MYSQLI: Variable parameter/result binding with prepared statements.

    - by Brian Warshaw
    In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can. Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the bind_params() or bind_result() methods. Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind. Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements. Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).

    Read the article

  • Linker error: wants C++ virtual base class destructor

    - by jdmuys
    Hi, I have a link error where the linker complains that my concrete class's destructor is calling its abstract superclass destructor, the code of which is missing. This is using GCC 4.2 on Mac OS X from XCode. I saw http://stackoverflow.com/questions/307352/g-undefined-reference-to-typeinfo but it's not quite the same thing. Here is the linker error message: Undefined symbols: "ConnectionPool::~ConnectionPool()", referenced from: AlwaysConnectedConnectionZPool::~AlwaysConnectedConnectionZPool()in RKConnector.o ld: symbol(s) not found collect2: ld returned 1 exit status Here is the abstract base class declaration: class ConnectionPool { public: static ConnectionPool* newPool(std::string h, short p, std::string u, std::string pw, std::string b); virtual ~ConnectionPool() =0; virtual int keepAlive() =0; virtual int disconnect() =0; virtual sql::Connection * getConnection(char *compression_scheme = NULL) =0; virtual void releaseConnection(sql::Connection * theConnection) =0; }; Here is the concrete class declaration: class AlwaysConnectedConnectionZPool: public ConnectionPool { protected: <snip data members> public: AlwaysConnectedConnectionZPool(std::string h, short p, std::string u, std::string pw, std::string b); virtual ~AlwaysConnectedConnectionZPool(); virtual int keepAlive(); // will make sure the connection doesn't time out. Call regularly virtual int disconnect(); // disconnects/destroys all connections. virtual sql::Connection * getConnection(char *compression_scheme = NULL); virtual void releaseConnection(sql::Connection * theConnection); }; Needless to say, all those members are implemented. Here is the destructor: AlwaysConnectedConnectionZPool::~AlwaysConnectedConnectionZPool() { printf("AlwaysConnectedConnectionZPool destructor call"); // nothing to destruct in fact } and also maybe the factory routine: ConnectionPool* ConnectionPool::newPool(std::string h, short p, std::string u, std::string pw, std::string b) { return new AlwaysConnectedConnectionZPool(h, p, u, pw, b); } I can fix this by artificially making my abstract base class concrete. But I'd rather do something better. Any idea? Thanks

    Read the article

  • Encapsulating user input of data for a class (C++)

    - by Dr. Monkey
    For an assignment I've made a simple C++ program that uses a superclass (Student) and two subclasses (CourseStudent and ResearchStudent) to store a list of students and print out their details, with different details shown for the two different types of students (using overriding of the display() method from Student). My question is about how the program collects input from the user of things like the student name, ID number, unit and fee information (for a course student) and research information (for research students): My implementation has the prompting for user input and the collecting of that input handled within the classes themselves. The reasoning behind this was that each class knows what kind of input it needs, so it makes sense to me to have it know how to ask for it (given an ostream through which to ask and an istream to collect the input from). My lecturer says that the prompting and input should all be handled in the main program, which seems to me somewhat messier, and would make it trickier to extend the program to handle different types of students. I am considering, as a compromise, to make a helper class that handles the prompting and collection of user input for each type of Student, which could then be called on by the main program. The advantage of this would be that the student classes don't have as much in them (so they're cleaner), but also they can be bundled with the helper classes if the input functionality is required. This also means more classes of Student could be added without having to make major changes to the main program, as long as helper classes are provided for these new classes. Also the helper class could be swapped for an alternative language version without having to make any changes to the class itself. What are the major advantages and disadvantages of the three different options for user input (fully encapsulated, helper class or in the main program)?

    Read the article

  • Spring Security ACL: NotFoundException from JDBCMutableAclService.createAcl

    - by user340202
    Hello, I've been working on this task for too long to abandon the idea of using Spring Security to achieve it, but I wish that the community will provide with some support that will help reduce the regret that I have for choosing Spring Security. Enough ranting and now let's get to the point. I'm trying to create an ACL by using JDBCMutableAclService.createAcl as follows: [code] public void addPermission(IWFArtifact securedObject, Sid recipient, Permission permission, Class clazz) { ObjectIdentity oid = new ObjectIdentityImpl(clazz.getCanonicalName(), securedObject.getId()); this.addPermission(oid, recipient, permission); } @Override @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_UNCOMMITTED, readOnly = false) public void addPermission(ObjectIdentity oid, Sid recipient, Permission permission) { SpringSecurityUtils.assureThreadLocalAuthSet(); MutableAcl acl; try { acl = this.mutableAclService.createAcl(oid); } catch (AlreadyExistsException e) { acl = (MutableAcl) this.mutableAclService.readAclById(oid); } // try { // acl = (MutableAcl) this.mutableAclService.readAclById(oid); // } catch (NotFoundException nfe) { // acl = this.mutableAclService.createAcl(oid); // } acl.insertAce(acl.getEntries().length, permission, recipient, true); this.mutableAclService.updateAcl(acl); } [/code] The call throws a NotFoundException from the line: [code] // Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc) Acl acl = readAclById(objectIdentity); [/code] I believe this is caused by something related to Transactional, and that's why I have tested with many TransactionDefinition attributes. I have also doubted the annotation and tried with declarative transaction definition, but still with no luck. One important point is that I have used the statement used to insert the oid in the database earlier in the method directly on the database and it worked, and also threw a unique constraint exception at me when it tried to insert it in the method. I'm using Spring Security 2.0.8 and IceFaces 1.8 (which doesn't support spring 3.0 but definetely supprorts 2.0.x, specially when I keep caling SpringSecurityUtils.assureThreadLocalAuthSet()). My AppServer is Tomcat 6.0, and my DB Server is MySQL 6.0 I wish to get back a reply soon because I need to get this task off my way

    Read the article

  • Error in connection in ruby.

    - by piemesons
    require 'rubygems' require 'mysql' db = Mysql.connect('localhost', 'root', '', 'mohit') //db.rb:4: undefined method `connect' for Mysql:Class (NoMethodError) //undefined method `real_connect' for Mysql:Class (NoMethodError) db.query("CREATE TABLE people ( id integer primary key, name varchar(50), age integer)") db.query("INSERT INTO people (name, age) VALUES('Chris', 25)") begin query = db.query('SELECT * FROM people') puts "There were #{query.num_rows} rows returned" query.each_hash do |h| puts h.inspect end rescue puts db.errno puts db.error end error i am geting is: undefined method `connect' for Mysql:Class (NoMethodError) OR undefined method `real_connect' for Mysql:Class (NoMethodError) EDIT return value of Mysql.methods ["private_class_method", "inspect", "name", "tap", "clone", "public_methods", "object_id", "__send__", "method_defined?", "instance_variable_defined?", "equal?", "freeze", "extend", "send", "const_defined?", "methods", "ancestors", "module_eval", "instance_method", "hash", "autoload?", "dup", "to_enum", "instance_methods", "public_method_defined?", "instance_variables", "class_variable_defined?", "eql?", "constants", "id", "instance_eval", "singleton_methods", "module_exec", "const_missing", "taint", "instance_variable_get", "frozen?", "enum_for", "private_method_defined?", "public_instance_methods", "display", "instance_of?", "superclass", "method", "to_a", "included_modules", "const_get", "instance_exec", "type", "<", "protected_methods", "<=>", "class_eval", "==", "class_variables", ">", "===", "instance_variable_set", "protected_instance_methods", "protected_method_defined?", "respond_to?", "kind_of?", ">=", "public_class_method", "to_s", "<=", "const_set", "allocate", "class", "new", "private_methods", "=~", "tainted?", "__id__", "class_exec", "autoload", "untaint", "nil?", "private_instance_methods", "include?", "is_a?"] return value of Mysql.methods(false) is []... blank array

    Read the article

  • Jersey, JAXB and getting an objectextending an abstract class as a parameter

    - by krajol
    I want to get an object as a parameter of a POST request. I got an abstract superclass that is called Promotion and subclasses Product and Percent. Here's how I try to get a request: @POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) @Path("promotion/") public Promotion createPromotion(Promotion promotion) { Product p = (Product) promotion; System.out.println(p.getPriceAfter()); return promotion; } and here's how I use JAXB in classes' definitions: @XmlRootElement(name="promotion") @XmlSeeAlso({Product.class,Percent.class}) public abstract class Promotion { //body } @XmlRootElement(name="promotion") public class Product extends Promotion { //body } @XmlRootElement(name="promotion") public class Percent extends Promotion { //body } So the problem now is when I send a POST request with a body like this: <promotion> <priceBefore>34.5</priceBefore> <marked>false</marked> <distance>44</distance> </promotion> and I try to cast it to Product (as in this case, fields 'marked' and 'distance' are from Promotion class and 'priceBefore' is from Product class) I get an Exception: java.lang.ClassCastException: Percent cannot be cast to Product. It seems like Percent is chosen as a 'default' subclass. Why is that and how can I get an object that is a Product?

    Read the article

  • C++ class derivation and superconstructor confusion

    - by LukeN
    Hey, in a tutorial C++ code, I found this particular piece of confusion: PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args), // <- Okay, Plasma = namespace, Applet = class m_svg(this), // <- A member function of class "Applet"? m_icon("document") // <- ditto? { m_svg.setImagePath("widgets/background"); // this will get us the standard applet background, for free! setBackgroundHints(DefaultBackground); resize(200, 200); } I'm not new to object oriented programming, so class derivation and super-classes are nothing complicated, but this syntax here got me confused. The header file defines the class like this: class PlasmaTutorial1 : public Plasma::Applet { Similar to above, namespace Plasma and class Applet. But what's the public doing there? I fear that I already know the concept but don't grasp the C++ syntax/way of doing it. In this question I picked up that these are called "superconstructors", at least that's what stuck in my memory, but I don't get this to the full extend. If we glance back at the first snippet, we see Constructor::Class(...) : NS::SuperClass(...), all fine 'till here. But what are m_svg(this), m_icon("document") doing there? Is this some kind of method to make these particular functions known to the derivated class? Is this part of C++ basics or more immediate? While I'm not completly lost in C++, I feel much more at home in C :) Most of the OOP I have done so far was done in D, Ruby or Python. For example in D I would just define class MyClass : MySuperClass, override what I needed to and call the super class' constructor if I'd need to.

    Read the article

  • I want a function to return a type of the subclass its invoked from

    - by Jay
    I want to have a function defined in a superclass that returns a value of the type of the subclass that is used to invoke the function. That is, say I have class A with a function plugh. Then I create subclasses B and C that extend A. I want B.plugh to return a B and C.plugh to return a C. Yes, they could return an A, but then the caller would have to either cast it to the right subtype, which is a pain when used a lot, or declare the receiving variable to be of the supertype, which loses type safety. So I was trying to do this with generics, writing something like this: class A<T extends A> { private T foo; public T getFoo() { return foo; } } class B extends A<B> { public void calcFoo() { foo=... whatever ... } } class C extends A<C> { public void calcFoo() { foo=... whatever ... } } This appears to work but it looks pretty ugly. For one thing, I get warnings on "class A". The compiler says that A is generic and I should specify the type. I guess it wants me to say "class A". But what would I put in for x? I think I could get stuck in an infinite loop here. It seems weird to write "class B extends A", but this causes no complaints, so maybe that's just fine. Is this the right way to do it? Is there a better way?

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >