Search Results

Search found 3956 results on 159 pages for 'constructor overloading'.

Page 9/159 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Error Instantiating an Inner Class in Parent's Constructor...

    - by stormin986
    In my application's main class (subclass of Application), I have a public inner class that simply contains 3 public string objects. In the parent class I declare an object of that inner class. public class MainApplication extends Application { public class Data { public String x; public String y; public String z; } private Data data; MainApplication() { data = new Data() data.x = "String"; } } After I instantiate the object in the constructor, I get a runtime error when I try to assign any of the inner class object's variables. Any idea what's up here??

    Read the article

  • Constructor with non-instance variable assistant?

    - by Robert Fischer
    I have a number of classes that look like this: class Foo(val:BasicData) extends Bar(val) { val helper = new Helper(val) val derived1 = helper.getDerived1Value() val derived2 = helper.getDerived2Value() } ...except that I don't want to hold onto an instance of "helper" beyond the end of the constructor. In Java, I'd do something like this: public class Foo { final Derived derived1, derived2; public Foo(BasicData val) { Helper helper = new Helper(val); derived1 = helper.getDerived1Value(); derived2 = helper.getDerived2Value(); } } So how do I do something like that in Scala? I'm aware of creating a helper object of the same name of the class with an apply method: I was hoping for something slightly more succinct.

    Read the article

  • C++ catch constructor exception

    - by aaa
    hi. I do not seem to understand how to catch constructor exception. Here is relevant code: struct Thread { rysq::cuda::Fock fock_; template<class iterator> Thread(const rysq::cuda::Centers &centers, const iterator (&blocks)[4]) : fock_() { if (!fock_) throw; } }; Thread *ct; try { ct = new Thread(centers_, blocks); } catch(...) { return false; } // catch never happens, So catch statement do not execute and I get unhandled exception. What did I do wrong? this is straight C++ using g++.

    Read the article

  • Disallow private constructor invocation in friend function

    - by user2907032
    Is there any way to not allow private construction in friend function, In case we do have private constructor with friend function in our class. Only Static method should be responsible for object creation and other than this compiler should flash error message #include <iostream> #include <memory> using namespace std; class a { public: void see () { cout<<"Motimaa"; } static a& getinstance() { static a instance; return instance; } private: a() {}; friend void access(); }; void access () { a obj; obj.see();//still friend function can access } int main() { a::getinstance().see(); access(); return 1; }

    Read the article

  • C# Closing a form during a constructor

    - by pm_2
    Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)? I have the following code: public partial class MyForm : Form { public MyForm() { if (MyFunc()) { this.Close(); } } } Which errors in Main(), here: static void Main() { ... // Following line errors Application.Run(new MyForm()); } I’ve tried checking the result of MyForm like this: static void Main() { ... MyForm frm = new MyForm(); if (frm != null) { // Following line errors Application.Run(frm); } } But that doesn’t seem to help. Can anyone tell me a way around this, please? Maybe a way to check the form to see if it still exists?

    Read the article

  • How do I get the default constructor value in a function

    - by lax
    public class AppXmlLogWritter { public int randomNumber; public string LogDateTime = ""; public AppXmlLogWritter() { Random random = new Random(); randomNumber = random.Next(9999); LogDateTime = DateTime.Now.ToString("yyyyMMdd HHmmss"); } public AppXmlLogWritter(int intLogIDPrefix, string strLogApplication, string strLogFilePath) { LogIDPrefix = intLogIDPrefix; LogApplication = strLogApplication; LogFilePath = strLogFilePath; } public void WriteXmlLog(string LogFlag) { string value=LogDateTime + randomNumber;**//Here i m getting 0 no date time and random number generated** } } AppXmlLogWritter objParameterized = new AppXmlLogWritter(1234, "LogApplication", "LogFilepath"); AppXmlLogWritter objParmeterlessConstr = new AppXmlLogWritter(); objParameterized.WriteXmlLog("0", "LogFlag"); How do I get the default constructor value in this function?

    Read the article

  • C# Constructor Problem When Using Generics

    - by Jimbo
    Please see an example of my code below: public class ScrollableCheckboxList { public List<ScrollableCheckboxItem> listitems; public void ScrollableCheckboxList<TModel>(IEnumerable<TModel> items, string valueField, string textField, string titleField) where TModel : class { listitems = new List<ScrollableCheckboxItem>(); foreach (TModel item in items) { Type t = typeof(TModel); PropertyInfo[] props = new [] { t.GetProperty(textField), t.GetProperty(valueField), t.GetProperty(titleField) }; listitems.Add(new ScrollableCheckboxItem { text = props[0].GetValue(item, null).ToString(), value = props[1].GetValue(item, null).ToString(), title = props[2].GetValue(item, null).ToString() }); } } } The code produces the following error: 'ScrollableCheckboxList': member names cannot be the same as their enclosing type This clearly means that there is a method in the class that has the same name as the class, but usually insinuates that the method is trying to return something (which is not allowed) In my case, all I have done is declare a constructor - why would this be a problem?

    Read the article

  • Copy Constructor in C++

    - by user265260
    i have this code #include <iostream> using namespace std; class Test{ public: int a; Test(int i=0):a(i){} ~Test(){ cout << a << endl; } Test(const Test &){ cout << "copy" << endl; } void operator=(const Test &){ cout << "=" << endl; } Test operator+(Test& p){ Test res(a+p.a); return res; } }; int main (int argc, char const *argv[]){ Test t1(10), t2(20); Test t3=t1+t2; return 0; } Output: 30 20 10 Why isnt the copy constructor called here?

    Read the article

  • Constructor Definition

    - by mctl87
    Ok so i have a class Vector: #include <cstdlib> class Vec { private: size_t size; int * ptab; public: Vec(size_t n); ~Vec() {delete [] ptab;} size_t size() const {return size;} int & operator[](int n) {return ptab[n];} int operator[](int n) const {return ptab[n];} void operator=(Vec const& v); }; inline Vec::Vec(size_t n) : size(n), ptab(new int[n]) { } and the problem is that in one of my homework exercises i have to extend constructor def, so all elements will be initialized with zeros. I thought i know the basics but cant get through this dynamic array -.- ps. sry for gramma and other mistakes ;)

    Read the article

  • CA2000 passing object reference to base constructor in C#

    - by Timothy
    I receive a warning when I run some code through Visual Studio's Code Analysis utility which I'm not sure how to resolve. Perhaps someone here has come across a similar issue, resolved it, and is willing to share their insight. I'm programming a custom-painted cell used in a DataGridView control. The code resembles: public class DataGridViewMyCustomColumn : DataGridViewColumn { public DataGridViewMyCustomColumn() : base(new DataGridViewMyCustomCell()) { } It generates the following warning: CA2000 : Microsoft.Reliability : In method 'DataGridViewMyCustomColumn.DataGridViewMyCustomColumn()' call System.IDisposable.Dispose on object 'new DataGridViewMyCustomCell()' before all references to it are out of scope. I understand it is warning me DataGridViewMyCustomCell (or a class that it inherits from) implements the IDisposable interface and the Dispose() method should be called to clean up any resources claimed by DataGridViewMyCustomCell when it is no longer. The examples I've seen on the internet suggest a using block to scope the lifetime of the object and have the system automatically dispose it, but base isn't recognized when moved into the body of the constructor so I can't write a using block around it... which I'm not sure I'd want to do anyway, since wouldn't that instruct the run time to free the object which could still be used later inside the base class? My question then, is the code okay as is? Or, how could it be refactored to resolve the warning? I don't want to suppress the warning unless it is truly appropriate to do so.

    Read the article

  • Temporary non-const istream reference in constructor (C++)

    - by Christopher Bruns
    It seems that a constructor that takes a non-const reference to an istream cannot be constructed with a temporary value in C++. #include <iostream> #include <sstream> using namespace std; class Bar { public: explicit Bar(std::istream& is) {} }; int main() { istringstream stream1("bar1"); Bar bar1(stream1); // OK on all platforms // compile error on linux, Mac gcc; OK on Windows MSVC Bar bar2(istringstream("bar2")); return 0; } This compiles fine with MSVC, but not with gcc. Using gcc I get a compile error: g++ test.cpp -o test test.cpp: In function ‘int main()’: test.cpp:18: error: no matching function for call to ‘Bar::Bar(std::istringstream)’ test.cpp:9: note: candidates are: Bar::Bar(std::istream&) test.cpp:7: note: Bar::Bar(const Bar&) Is there something philosophically wrong with the second way (bar2) of constructing a Bar object? It looks nicer to me, and does not require that stream1 variable that is only needed for a moment.

    Read the article

  • Ruby - calling constructor without arguments & removal of new line characters

    - by Raj
    I am a newbie at Ruby, I have written down a sample program. I dont understand the following: Why constructor without any arguments are not called in Ruby? How do we access the class variable outside the class' definition? Why does it always append newline characters at the end of the string? How do we strip it? Code: class Employee attr_reader :empid attr_writer :empid attr_writer :name def name return @name.upcase end attr_accessor :salary @@employeeCount = 0 def initiaze() @@employeeCount += 1 puts ("Initialize called!") end def getCount return @@employeeCount end end anEmp = Employee.new print ("Enter new employee name: ") anEmp.name = gets() print ("Enter #{anEmp.name}'s employee ID: ") anEmp.empid = gets() print ("Enter salary for #{anEmp.name}: ") anEmp.salary = gets() theEmpName = anEmp.name.split.join("\n") theEmpID = anEmp.empid.split.join("\n") theEmpSalary = anEmp.salary.split.join("\n") anEmp = Employee.new() anEmp = Employee.new() theCount = anEmp.getCount puts ("New employee #{theEmpName} with employee ID #{theEmpID} has been enrolled, welcome to hell! You have been paid as low as $ #{theEmpSalary}") puts ("Total number of employees created = #{theCount}") Output: Enter new employee name: Lionel Messi Enter LIONEL MESSI 's employee ID: 10 Enter salary for LIONEL MESSI : 10000000 New employee LIONEL MESSI with employee ID 10 has been enrolled, welcome to hell! You have been paid as low as $ 10000000 Total number of employees created = 0 Thanks

    Read the article

  • stealing inside the move constructor

    - by FredOverflow
    During the implementation of the move constructor of a toy class, I noticed a pattern: array2D(array2D&& that) { data_ = that.data_; that.data_ = 0; height_ = that.height_; that.height_ = 0; width_ = that.width_; that.width_ = 0; size_ = that.size_; that.size_ = 0; } The pattern obviously being: member = that.member; that.member = 0; So I wrote a preprocessor macro to make stealing less verbose and error-prone: #define STEAL(member) member = that.member; that.member = 0; Now the implementation looks as following: array2D(array2D&& that) { STEAL(data_); STEAL(height_); STEAL(width_); STEAL(size_); } Are there any downsides to this? Is there a cleaner solution that does not require the preprocessor?

    Read the article

  • Inheritance and choose constructor from base class

    - by myle
    My question is rather simple, but I am stuck. How can I choose the desired constructor from base class? // node.h #ifndef NODE_H #define NODE_H #include <vector> // definition of an exception-class class WrongBoundsException { }; class Node { public: ... Node(double, double, std::vector<double>&) throw (WrongBoundsException); ... }; #endif // InternalNode.h #ifndef INTERNALNODE_H #define INTERNALNODE_H #include <vector> #include "Node.h" class InternalNode : public Node { public: // the position of the leftmost child (child left) int left_child; // the position of the parent int parent; InternalNode(double, double, std::vector<double>&, int parent, int left_child) throw (WrongBoundsException); private: int abcd; }; #endif // InternalNode.cpp #include "InternalNode.h" #define UNDEFINED_CHILD -1 #define ROOT -1 // Here is the problem InternalNode::InternalNode(double a, double b, std::vector<double> &v, int par, int lc) throw (WrongBoundsException) : Node(a, b, v), parent(par), left_child(lc) { std::cout << par << std::endl; } I get: $ g++ InternalNode.cpp InternalNode.cpp:16: error: declaration of ‘InternalNode::InternalNode(double, double, std::vector &, int, int) throw (WrongBoundsException)’ throws different exceptions InternalNode.h:17: error: from previous declaration ‘InternalNode::InternalNode(double, double, std::vector &, int, int)’ UPDATE 0: Fixed missing : UPDATE 1: Fixed throw exception

    Read the article

  • Copy constructor demo (crashing...)

    - by AKN
    Here is the program... class CopyCon { public: char *name; CopyCon() { name = new char; } CopyCon(const CopyCon &objCopyCon) { name = new char; _tcscpy(name,objCopyCon.name); } ~CopyCon() { if( name != NULL ) { delete name; name = NULL; } } }; int main() { CopyCon objCopyCon1; objCopyCon1.name = "Hai"; CopyCon objCopyCon2(objCopyCon1); objCopyCon1.name = "Hello"; cout<<objCopyCon2.name<<endl; return 0; } Once the code execution completes, when the destructor called, it crashes on 'delete' saying... Debug Error! Program: ... HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990. CRT detected that the application wrote to memory after end of heap buffer. (Press Retry to debug the application) Don't we have to clear the heap memory in destructor. What's wrong with this program? Pls someone help! Copy constructor works perfectly as intended. But still... !?

    Read the article

  • C++ Initialize array in constructor EXC_BAD_ACCESS

    - by user890395
    I'm creating a simple constructor and initializing an array: // Construtor Cinema::Cinema(){ // Initalize reservations for(int i = 0; i < 18; i++){ for(int j = 0; j < 12; j++){ setReservation(i, j, 0); } } // Set default name setMovieName("N/A"); // Set default price setPrice(8); } The setReservation function: void Cinema::setReservation(int row, int column, int reservation){ this->reservations[row][column] = reservation; } The setMovieName function: void Cinema::setMovieName(std::string movieName){ this->movieName = movieName; } For some odd reason when I run the program, the setMovieName function gives the following error: "Program Received Signal: EXC_BAD_ACCESS" If I take out the for-loop that initializes the array of reservations, the problem goes away and the movie name is set without any problems. Any idea what I'm doing wrong? This is the Cinema.h file: #ifndef Cinema_h #define Cinema_h class Cinema{ private: int reservations[17][11]; std::string movieName; float price; public: // Construtor Cinema(); // getters/setters int getReservation(int row, int column); int getNumReservations(); std::string getMovieName(); float getPrice(); void setReservation(int row, int column, int reservation); void setMovieName(std::string movieName); void setPrice(float price); }; #endif

    Read the article

  • Should a C++ constructor do real work?

    - by Wade Williams
    I'm strugging with some advice I have in the back of my mind but for which I can't remember the reasoning. I seem to remember at some point reading some advice (can't remember the source) that C++ constructors should not do real work. Rather, they should initialize variables only. The advice when on to explain that real work should be done in some sort of init() method, to be called separately after the instance was created. The situation is I have a class that represents a hardware device. It makes logical sense to me for the constructor to call the routines that query the device in order to build up the instance variables that describe the device. In other words, once new instantiates the object, the developer receives an object which is ready to be used, no separate call to object-init() required. Is there a good reason why constructors shouldn't do real work? Obviously it could slow allocation time, but that wouldn't be any different if calling a separate method immediately after allocation. Just trying to figure out what gotchas I not currently considering that might have lead to such advice.

    Read the article

  • Is it bad practise to initialise fields outside of an explicit constructor

    - by MrTortoise
    So its monday and we are arguing about coding practises. The examples here are a litttle too simple, but the real deal has several constructors. In order to initialise the simple values (eg dates to their min value) I have moved the code out of the constructors and into the field definitions. public class ConstructorExample { string _string = "John"; } public class ConstructorExample2 { string _string; public ConstructorExample2() { _string = "John"; } } How should it be done by the book. I tend to be very case by case and so am maybe a little lax abotu this kind of thing. However i feel that accams razor tells me to move the initialisation out of multiple constructors. Of course I could always move this shared initialisation into a private method. The question is essentially ... is initialising fields where they are defined as opposed to the constructor bad in any way? The argument I am facing is one of error handling, but i do not feel it is relevant as there are no possible exceptions that won't be picked up at compile time.

    Read the article

  • calling constructor of the class in the destructor of the same class

    - by dicaprio
    Experts !! I know this question is one of the lousy one , but still I dared to open my mind , hoping I would learn from all. I was trying some examples as part of my routine and did this horrible thing, I called the constructor of the class from destructor of the same class. I don't really know if this is ever required in real programming , I cant think of any real time scenarios where we really need to call functions/CTOR in our destructor. Usually , destructor is meant for cleaning up. If my understanding is correct, why the compiler doesn't complain ? Is this because it is valid for some good reasons ? If so what are they ? I tried on Sun Forte, g++ and VC++ compiler and none of them complain about it. using namespace std; class test{ public: test(){ cout<<"CTOR"<<endl; } ~test() {cout<<"DTOR"<<endl; test(); }};

    Read the article

  • copy C'tor with operator= | C++

    - by user2266935
    I've got this code here: class DerivedClass : public BaseClass { SomeClass* a1; Someclass* a2; public: //constructors go here ~DerivedClass() { delete a1; delete a2;} // other functions go here .... }; My first question is as follows: Can I write an "operator=" to "DerivedClass" ? (if your answer is yes, could you show me how?) My second question is: If the answer to the above is yes, could you show me how to make an "copy c'tor" using the "operator=" that you wrote beforehand (if that is even possible)? Your help would be much appreciated !

    Read the article

  • What is constructor injection?

    - by TheSilverBullet
    I have been looking at the terms constructor injection and dependency injection while going through articles on (Service locator) design patterns. When I googled about constructor injection, I got unclear results, which prompted me to check in here. What is constructor injection? Is this a specific type of dependency injection? A canonical example would be a great help! Edit Revisiting this questions after a gap of a week, I can see how lost I was... Just in case anyone else pops in here, I will update the question body with a little learning of mine. Please do feel free to comment/correct. Constructor injection and property injection are two types of Dependency Injection.

    Read the article

  • C++: Retriving values of static const variables at a constructor of a static variable

    - by gilbertc
    I understand that the code below would result segmentation fault because at the cstr of A, B::SYMBOL was not initialized yet. But why? In reality, A is an object that serves as a map that maps the SYMBOLs of classes like B to their respective IDs. C holds this map(A) static-ly such that it can provide the mapping as a class function. The primary function of A is to serve as a map for C that initializes itself at startup. How should I be able to do that without segmentation fault, provided that I can still use B::ID and B::SYMBOL in the code (no #define pls)? Thanks! Gil. class A { public: A() { std::cout<<B::ID<<std::endl; std::cout<<B::SYMBOL<<std::endl; } }; class B { public: static const int ID; static const std::string SYMBOL; } const int B::ID = 1; const std::string B::SYMBOL = "B"; class C { public: static A s_A; }; A C::s_A; int main(int c, char** p) { }

    Read the article

  • add methods in subclasses within the super class constructor

    - by deamon
    I want to add methods (more specifically: method aliases) automatically to Python subclasses. If the subclass defines a method named 'get' I want to add a method alias 'GET' to the dictionary of the subclass. To not repeat myself I'd like to define this modifation routine in the base class. But if I check in the base class init method, there is no such method, since it is defined in the subclass. It will become more clear with some source code: class Base: def __init__(self): if hasattr(self, "get"): setattr(self, "GET", self.get) class Sub(Base): def get(): pass print(dir(Sub)) Output: ['__doc__', '__init__', '__module__', 'get'] It should also contain 'GET'. Is there a way to do it within the base class?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >