Search Results

Search found 597 results on 24 pages for 'constructors'.

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

  • C++ syntax of constructors " 'Object1 a (1, Object1(2))''

    - by osgx
    Hello I have a such syntax in program class Object1 : BaseClass { BaseClass *link; int i; public: Object1(int a){i=a;} Object1(int a, Object1 /*place1*/ o) {i=a; link= &o;} }; int main(){ Object1 a(1, /*place2*/ Object1(2)); ... } What do I need in place1? I want to save a link (pointer) to the second object in the first object. Should I use in place1 reference "&"? What type will have "Object1(2)" in place2? Is it a constructor of the anonymous object? Will it have a "auto" storage type?

    Read the article

  • C++: Could Polymorphic Copy Constructors work?

    - by 0xC0DEFACE
    Consider: class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = new A( *b1 ); // ERROR...but what if it could work? return 0; } Would C++ be broken if "new A( b1 )" was able to resolve to creating a new B copy and returning an A? Would this even be useful?

    Read the article

  • c++ constructors

    - by aharont
    i wrote this code: class A { public: A(){d=2.2;cout<<d;} A(double d):d(d){cout<<d;} double getD(){return d;} private: double d; }; class Bing { public: Bing(){a=A(5.3);} void f(){cout<<a.getD();} private: A a; }; int main() { Bing b; b.f(); } i get the output: 2.2 5.3 5.3 instead of 5.3 5.3. it's something in the constructor.... wahy am i getting this? how can i fix it?

    Read the article

  • C++ pointers and constructors

    - by lego69
    if I have this snippet of the code A a1(i); A a2 = a1; A *pa1 = new A(a2); can somebody please explain what exactly the last line does, it makes copy of the a2 and pointer for this new object is pa1 or it just creates pointer for a2, thanks in advance

    Read the article

  • Constructors from extended class in Java

    - by Crystal
    I'm having some trouble with a hw assignment. In one assignment, we had to create a Person class. Mine was: public class Person { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return 7 * firstName.hashCode() + 11 * lastName.hashCode() + 13 * telephone.hashCode() + 15 * email.hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } Now we have to extend that class and use that class in our constructor. The function protoype is: public CarLoan(Person client, double vehiclePrice, double downPayment, double salesTax, double interestRate, CAR_LOAN_TERMS length) I'm confused on how I use the Person constructor from the superclass. I cannot necessarily do super(client); in my constructor which is what the book did with some primitive types in their example. Not sure what the correct thing to do is... Any thoughts? Thanks!

    Read the article

  • can constructors actually return Strings?

    - by elwynn
    Hi all, I have a class called ArionFileExtractor in a .java file of the same name. public class ArionFileExtractor { public String ArionFileExtractor (String fName, String startText, String endText) { String afExtract = ""; // Extract string from fName into afExtract in code I won't show here return afExtract; } However, when I try to invoke ArionFileExtractor in another .java file, as follows: String afe = ArionFileExtractor("gibberish.txt", "foo", "/foo"); NetBeans informs me that there are incompatible types and that java.lang.String is required. But I coded ArionFileExtractor to return the standard string type, which is java.lang.string. I am wondering, can my ArionFileExtractor constructor legally return a String? I very much appreciate any tips or pointers on what I'm doing wrong here.

    Read the article

  • How can I add a field with an array value to my Perl object?

    - by superstar
    What's the difference between these two constructors in perl? 1) sub new { my $class = shift; my $self = {}; $self->{firstName} = undef; $self->{lastName} = undef; $self->{PEERS} = []; bless ($self, $class); return $self; } 2) sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; bless $self, $class; return $self; } I am using the second one so far, but I need to implement the PEERS array in the second one? How do I do it with the second constructor and how can we use get and set methods on those array variables?

    Read the article

  • Passing IDisposable objects through constructor chains

    - by Matt Enright
    I've got a small hierarchy of objects that in general gets constructed from data in a Stream, but for some particular subclasses, can be synthesized from a simpler argument list. In chaining the constructors from the subclasses, I'm running into an issue with ensuring the disposal of the synthesized stream that the base class constructor needs. Its not escaped me that the use of IDisposable objects this way is possibly just dirty pool (plz advise?) for reasons I've not considered, but, this issue aside, it seems fairly straightforward (and good encapsulation). Codes: abstract class Node { protected Node (Stream raw) { // calculate/generate some base class properties } } class FilesystemNode : Node { public FilesystemNode (FileStream fs) : base (fs) { // all good here; disposing of fs not our responsibility } } class CompositeNode : Node { public CompositeNode (IEnumerable some_stuff) : base (GenerateRaw (some_stuff)) { // rogue stream from GenerateRaw now loose in the wild! } static Stream GenerateRaw (IEnumerable some_stuff) { var content = new MemoryStream (); // molest elements of some_stuff into proper format, write to stream content.Seek (0, SeekOrigin.Begin); return content; } } I realize that not disposing of a MemoryStream is not exactly a world-stopping case of bad CLR citizenship, but it still gives me the heebie-jeebies (not to mention that I may not always be using a MemoryStream for other subtypes). It's not in scope, so I can't explicitly Dispose () it later in the constructor, and adding a using statement in GenerateRaw () is self-defeating since I need the stream returned. Is there a better way to do this? Preemptive strikes: yes, the properties calculated in the Node constructor should be part of the base class, and should not be calculated by (or accessible in) the subclasses I won't require that a stream be passed into CompositeNode (its format should be irrelevant to the caller) The previous iteration had the value calculation in the base class as a separate protected method, which I then just called at the end of each subtype constructor, moved the body of GenerateRaw () into a using statement in the body of the CompositeNode constructor. But the repetition of requiring that call for each constructor and not being able to guarantee that it be run for every subtype ever (a Node is not a Node, semantically, without these properties initialized) gave me heebie-jeebies far worse than the (potential) resource leak here does.

    Read the article

  • Specifying properties when initialising

    - by maxp
    void Foo() { bool ID = "test"; var testctrl = new Control() {ID = (ID**=="abc"?ID:ID**)}; } Is it possible to get the value of ID** in the code above? The problem is they both have the same property names. Please ignore the fact the specific ID assignment is pointless, im just using it as an example.

    Read the article

  • Calling function using 'new' is less expensive than without it?

    - by Matthew Taylor
    Given this very familiar model of prototypal construction: function Rectangle(w,h) { this.width = w; this.height = h; } Rectangle.prototype.area = function() { return this.width * this.height; }; Can anyone explain why calling "new Rectangle(2,3)" is consistently 10x FASTER than calling "Rectangle(2,3)" without the 'new' keyword? I would have assumed that because new adds more complexity to the execution of a function by getting prototypes involved, it would be slower. Example: var myTime; function startTrack() { myTime = new Date(); } function stopTrack(str) { var diff = new Date().getTime() - myTime.getTime(); println(str + ' time in ms: ' + diff); } function trackFunction(desc, func, times) { var i; if (!times) times = 1; startTrack(); for (i=0; i<times; i++) { func(); } stopTrack('(' + times + ' times) ' + desc); } var TIMES = 1000000; trackFunction('new rect classic', function() { new Rectangle(2,3); }, TIMES); trackFunction('rect classic (without new)', function() { Rectangle(2,3); }, TIMES); Yields (in Chrome): (1000000 times) new rect classic time in ms: 33 (1000000 times) rect classic (without new) time in ms: 368 (1000000 times) new rect classic time in ms: 35 (1000000 times) rect classic (without new) time in ms: 374 (1000000 times) new rect classic time in ms: 31 (1000000 times) rect classic (without new) time in ms: 368

    Read the article

  • Returning in a static initializer

    - by Martijn Courteaux
    Hello, This isn't valid code: public class MyClass { private static boolean yesNo = false; static { if (yesNo) { System.out.println("Yes"); return; // The return statement is the problem } System.exit(0); } } This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this? So the reason why I should do return is to end constructing there. Thanks

    Read the article

  • Creating a list in Python- something sneaky going on?

    - by GlenCrawford
    Apologies if this doesn't make any sense, I'm very new to Python! From testing in an interpreter, I can see that list() and [] both produce an empty list: >>> list() [] >>> [] [] From what I've learned so far, the only way to create an object is to call its constructor (__init__), but I don't see this happening when I just type []. So by executing [], is Python then mapping that to a call to list()?

    Read the article

  • Returning in a static class constructor

    - by Martijn Courteaux
    Hello, This isn't valid code: public class MyClass { private static boolean yesNo = false; static { if (yesNo) { System.out.println("Yes"); return; // The return statement is the problem } System.exit(0); } } This is a stupid example, but in a static class constructor we can't return;. Why? Are there good reasons for this? Does someone know something more about this? So the reason why I should do return is to end constructing there. Thanks

    Read the article

  • Refactor throwing not null exception if using a method that has a dependency on a certain contructor

    - by N00b
    In the method below the second constructor accepts a ForumThread object which the IncrementViewCount() method uses. There is a dependency between the method and that particular constructor. Without extracting into a new private method the null check in IncrementViewCount() and LockForumThread() (plus other methods not shown) is there some simpler re-factoring I can do or the implementation of a better design practice for this method to guard against the use of the wrong constructor with these dependent methods? Thank you for any suggestions in advance. private readonly IThread _forumLogic; private readonly ForumThread _ft; public ThreadLogic(IThread forumLogic) : this(forumLogic, null) { } public ThreadLogic(IThread forumLogic, ForumThread ft) { _forumLogic = forumLogic; _ft = ft; } public void Create(ForumThread ft) { _forumLogic.SaveThread(ft); } public void IncrementViewCount() { if (_ft == null) throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor"); lock (_ft) { _ft.ViewCount = _ft.ViewCount + 1; _forumLogic.SaveThread(_ft); } } public void LockForumThread() { if (_ft == null) throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor"); _ft.ThreadLocked = true; _forumLogic.SaveThread(_ft); }

    Read the article

  • StructureMap - Injecting a dependency into a base class?

    - by David
    In my domain I have a handful of "processor" classes which hold the bulk of the business logic. Using StructureMap with default conventions, I inject repositories into those classes for their various IO (databases, file system, etc.). For example: public interface IHelloWorldProcessor { string HelloWorld(); } public class HelloWorldProcessor : IHelloWorldProcessor { private IDBRepository _dbRepository; public HelloWorldProcessor(IDBRepository dbRepository) { _dbRepository = dbrepository; } public string HelloWorld(){ return _dbRepository.GetHelloWorld(); } } Now, there are some repositories that I'd like to be available to all processors, so I made a base class like this: public class BaseProcessor { protected ICommonRepository _commonRepository; public BaseProcessor(ICommonRepository commonRepository) { _commonRepository = commonRepository; } } But when my other processors inherit from it, I get a compiler error on each one saying that there's no constructor for BaseProcessor which takes zero arguments. Is there a way to do what I'm trying to do here? That is, to have common dependencies injected into a base class that my other classes can use without having to write the injections into each one?

    Read the article

  • How can I create a generic constructor? (ie. BaseClass.FromXml(<param>)

    - by SofaKng
    I'm not sure how to describe this but I'm trying to create a base class that contains a shared (factory) function called FromXml. I want this function to instantiate an object of the proper type and then fill it via an XmlDocument. For example, let's say I have something like this: Public Class XmlObject Public Shared Function FromXml(ByVal source as XmlDocument) As XmlObject // <need code to create SPECIFIC TYPE of object and return it End Function End Class Public Class CustomObject Inherits XmlObject End Class I'd like to be able to do something like this: Dim myObject As CustomObject = CustomObject.FromXml(source) Is this possible?

    Read the article

  • correct way of initializing variables

    - by OVERTONE
    ok this is just a shot in the dark but it may be the cause of most of the errors ive gotten. when your initializing something. lets say a smal swing program. would it go liek this variables here { private Jlist contactList; String [] contactArray; ArrayList <String> contactArrayList; ResultSet namesList constructor here public whatever() { GridLayout aGrid = new GridLayout(2,2,10,10); contact1 = new String(); contact2 = new String(); contact3 = new String(); contactArrayList = new ArrayList<String>(); // is something supposed too go in the () of this JList? contactList = new JList(); contactArray = new String[5]; from1 =new JLabel ("From: " + contactArray[1]); gridlayout.add(components)// theres too many components to write onto SO. } // methods here public void fillContactsGui() { createConnection(); ArrayList<String> contactsArrayList = new ArrayList<String>(); while (namesList.next()) { contactArrayList.add(namesList.getString(1)); ContactArray[1] = namesList[1]; } } i know this is probably a huge beginner question but this is the code ive gotten used too. im initializing thigns three and fours times without meaning too because im not sure where they gp. can anyone shed some light on this? p.s. sorry for the messy sample code. i done my best.

    Read the article

  • a constructor as a delegate - is it possible in C#?

    - by akavel
    I have a class like below: class Foo { public Foo(int x) { ... } } and I need to pass to a certain method a delegate like this: delegate Foo FooGenerator(int x); Is it possible to pass the constructor directly as a FooGenerator value, without having to type: delegate(int x) { return new Foo(x); } ? EDIT: For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.

    Read the article

  • How can one enforce calling a base class function after derived class constructor?

    - by Mike Elkins
    I'm looking for a clean C++ idiom for the following situation: class SomeLibraryClass { public: SomeLibraryClass() { /* start initialization */ } void addFoo() { /* we are a collection of foos */ } void funcToCallAfterAllAddFoos() { /* Making sure this is called is the issue */ } }; class SomeUserClass : public SomeLibraryClass { public: SomeUserClass() { addFoo(); addFoo(); addFoo(); // SomeUserClass has three foos. } }; class SomeUserDerrivedClass : public SomeUserClass { public: SomeUserDerrivedClass() { addFoo(); // This one has four foos. } }; So, what I really want is for SomeLibraryClass to enforce the calling of funcToCallAfterAllAddFoos at the end of the construction process. The user can't put it at the end of SomeUserClass::SomeUserClass(), that would mess up SomeUserDerrivedClass. If he puts it at the end of SomeUserDerrivedClass, then it never gets called for SomeUserClass. To further clarify what I need, imagine that /* start initialization */ acquires a lock, and funcToCallAfterAllAddFoos() releases a lock. The compiler knows when all the initializations for an object are done, but can I get at that information by some nice trick?

    Read the article

  • VB.Net calling New without assigning value

    - by dcp
    In C# I can do this: new SomeObjectType("abc", 10); In other words, I can call new without assigning the created instance to any variable. However, in VB.Net it seems I cannot do the same thing. New SomeObjectType("abc", 10) ' syntax error Is there a way to do this in VB.Net?

    Read the article

  • Constructor initialising an array of subobjects?

    - by ojw
    Say I have several objects within a class, each of which needs constructing with a different value. I can write something like this: class b { public: b(int num) { // 1 for a.b1, and 2 for a.b2 } }; class a { public: b b1; b b2; a() : b1(1), b2(2) { } }; However, is it possible to do the same thing if those multiple objects are stored in an array? My first attempt at it doesn't compile: class a { public: b bb[2]; a() : bb[0](1), bb[1](2) { } };

    Read the article

  • How to differentiate two constructors with the same parameters?

    - by cibercitizen1
    Suppose we want two constructors for a class representing complex numbers: Complex (double re, double img) // construct from cartesian coordinates Complex (double A, double w) // construct from polar coordinates but the parameters (number and type) are the same: what is the more elegant way to identify what is intended? Adding a third parameter to one of the constructors?

    Read the article

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