Search Results

Search found 3493 results on 140 pages for 'constructor'.

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

  • 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

  • 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

  • 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

  • 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

  • Passing constructor arguments when using StructureMap

    - by Mosh
    Hello, I'm using StructureMap for my DI. Imagine I have a class that takes 1 argument like: public class ProductProvider : IProductProvider { public ProductProvider(string connectionString) { .... } } I need to specify the "connectionString at run-time when I get an instance of IProductProvider. I have configured StructureMap as follows: ForRequestedType<IProductProvider>.TheDefault.Is.OfConcreteType<ProductProvider>(). WithCtorArgument("connectionString"); However, I don't want to call EqualTo("something...") method here as I need some facility to dynamically specify this value at run-time. My question is: how can I get an instance of IProductProvider by using ObjectFactory? Currently, I have something like: ObjectFactory.GetInstance<IProductProvider>(); But as you know, this doesn't work... Any advice would be greatly appreciated.

    Read the article

  • Copy constructor demo (crashing... case 2)

    - by AKN
    Please have a glance at this program: class CopyCon { public: char *name; CopyCon() { name = new char[20]; name = "Hai";//_tcscpy(name,"Hai"); } CopyCon(const CopyCon &objCopyCon) { name = new char[_tcslen(objCopyCon.name)+1]; _tcscpy(name,objCopyCon.name); } ~CopyCon() { if( name != NULL ) { delete[] name; name = NULL; } } }; int main() { CopyCon obj1; CopyCon obj2(obj1); cout<<obj1.name<<endl; cout<<obj2.name<<endl; } This program crashes on execution. Error: "Expression: _BLOCK_TYPE_IS_VALID(pHead-nBlockUse)" If I assign "Hai" to name using aasignment operator, its crashing. Where as when I use string func _tcscpy to assign "Hai" to name, its working perfectly. Can some one explain why so?

    Read the article

  • Assignment operator that calls a constructor is broken

    - by Delan Azabani
    I've implemented some of the changes suggested in this question, and (thanks very much) it works quite well, however... in the process I've seemed to break the post-declaration assignment operator. With the following code: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } I get a nice "testing cafe´" message. However, if I modify the code slightly so that the const char * conversion is done separately, post-declaration: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d; d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } the ustring named d becomes blank, and all that is output is "testing ". My new code has three constructors, one void (which is probably the one being incorrectly used, and is used in the operator+ function), one that takes a const ustring &, and one that takes a const char *. The following is my new library code: #include <cstdlib> #include <cstring> class ustring { int * values; long len; public: long length() { return len; } ustring() { len = 0; values = (int *) malloc(0); } ustring(const ustring &input) { len = input.len; values = (int *) malloc(sizeof(int) * len); for (long i = 0; i < len; i++) values[i] = input.values[i]; } ustring operator=(ustring input) { ustring result(input); return result; } ustring(const char * input) { values = (int *) malloc(0); long s = 0; // s = number of parsed chars int a, b, c, d, contNeed = 0, cont = 0; for (long i = 0; input[i]; i++) if (input[i] < 0x80) { // ASCII, direct copy (00-7f) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = input[i]; } else if (input[i] < 0xc0) { // this is a continuation (80-bf) if (cont == contNeed) { // no need for continuation, use U+fffd values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } cont = cont + 1; values[s - 1] = values[s - 1] | ((input[i] & 0x3f) << ((contNeed - cont) * 6)); if (cont == contNeed) cont = contNeed = 0; } else if (input[i] < 0xc2) { // invalid byte, use U+fffd (c0-c1) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } else if (input[i] < 0xe0) { // start of 2-byte sequence (c2-df) contNeed = 1; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x1f) << 6; } else if (input[i] < 0xf0) { // start of 3-byte sequence (e0-ef) contNeed = 2; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x0f) << 12; } else if (input[i] < 0xf5) { // start of 4-byte sequence (f0-f4) contNeed = 3; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x07) << 18; } else { // restricted or invalid (f5-ff) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } len = s; } ustring operator=(const char * input) { ustring result(input); return result; } ustring operator+(ustring input) { ustring result; result.len = len + input.len; result.values = (int *) malloc(sizeof(int) * result.len); for (long i = 0; i < len; i++) result.values[i] = values[i]; for (long i = 0; i < input.len; i++) result.values[i + len] = input.values[i]; return result; } ustring operator[](long index) { ustring result; result.len = 1; result.values = (int *) malloc(sizeof(int)); result.values[0] = values[index]; return result; } char * encode() { char * r = (char *) malloc(0); long s = 0; for (long i = 0; i < len; i++) { if (values[i] < 0x80) r = (char *) realloc(r, s + 1), r[s + 0] = char(values[i]), s += 1; else if (values[i] < 0x800) r = (char *) realloc(r, s + 2), r[s + 0] = char(values[i] >> 6 | 0x60), r[s + 1] = char(values[i] & 0x3f | 0x80), s += 2; else if (values[i] < 0x10000) r = (char *) realloc(r, s + 3), r[s + 0] = char(values[i] >> 12 | 0xe0), r[s + 1] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 2] = char(values[i] & 0x3f | 0x80), s += 3; else r = (char *) realloc(r, s + 4), r[s + 0] = char(values[i] >> 18 | 0xf0), r[s + 1] = char(values[i] >> 12 & 0x3f | 0x80), r[s + 2] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 3] = char(values[i] & 0x3f | 0x80), s += 4; } return r; } };

    Read the article

  • jQuery.extend() not giving deep copy of object formed by constructor

    - by two7s_clash
    I'm trying to use this to clone a complicated Object. The object in question has a property that is an array of other Objects, and each of these have properties of different types, mostly primitives, but a couple further Objects and Arrays. For example, an ellipsed version of what I am trying to clone: var asset = new Assets(); function Assets() { this.values = []; this.sectionObj = Section; this.names = getNames; this.titles = getTitles; this.properties = getProperties; ... this.add = addAsset; function AssetObj(assetValues) { this.name = ""; this.title = ""; this.interface = ""; ... this.protected = false; this.standaloneProtected = true; ... this.chaptersFree = []; this.chaptersUnavailable = []; ... this.mediaOptions = { videoWidth: "", videoHeight: "", downloadMedia: true, downloadMediaExt: "zip" ... } this.chaptersAvailable = []; if (typeof assetValues == "undefined") { return; } for (var name in assetValues) { if (typeof assetValues[name] == "undefined") { this[name] = ""; } else { this[name] = assetValues[name]; } } ... function Asset() { return new AssetObj(); } ... function getProperties() { var propertiesArray = new Array(); for (var property in this.values[0]) { propertiesArray.push(property); } return propertiesArray; } ... function addAsset(assetValues) { var newValues; newValues = new AssetObj(assetValues); this.values.push(newValues); } } When I do var copiedAssets = $.extend(true, {}, assets); copiedAssets.values == [], while assets.values == [Object { name="section_intro", more...}, Object { name="select_textbook", more...}, Object { name="quiz", more...}, 11 more...] When I do var copiedAssets = $.extend( {}, assets); all copiedAssets.values.[X].properties are just pointers to the value in assets. What I want is a true deep copy all the way down. What am I missing? Do I need to write a custom extend function? If so, any recommended patterns?

    Read the article

  • Copy constructor, objects, pointers

    - by Pauff
    Let's say I have this: SolutionSet(const SolutionSet &solutionSet) { this->capacity_ = solutionSet.capacity_; this->solutionsList_ = solutionSet.solutionsList_; // <-- } And solutionsList_ is a vector<SomeType*> vect*. What is the correct way to copy that vector (I suppose that way I'm not doing it right..)?

    Read the article

  • StructureMap: Calling repository constructor based on RouteData

    - by FreshCode
    I'm implementing a multi-tenant ASP.NET MVC application and using StructureMap for DI where my repositories depend on an ITenantContext interface, which depends on RouteData (or a base controller property). How do I tell StructureMap to construct TenantContext(tenantID); where tenantID is derived from my RouteData or some base controller property? Given the following route: {tenant}/{controller}/{action} My base controller retrieves and stores the correct Tenant based on the {tenant} URL parameter. Using Tenant, a repository with an ITenantContext can be constructed to retrieve only data that is relevant to that tenant. Based on the other DI questions, AbstractFactory could be a solution?solution?

    Read the article

  • C++ Constructor initialization list strangeness

    - by Andy
    I have always been a good boy when writing my classes, prefixing all member variables with m_: class Test { int m_int1; int m_int2; public: Test(int int1, int int2) : m_int1(int int1), m_int2(int int2) {} }; void main() { Test t(10, 20); // Just an example } However, recently I forgot to do that and ended up writing: class Test { int int1; int int2; public: // Very questionable, but of course I meant to assign ::int1 to this->int1! Test(int int1, int int2) : int1(int1), int2(int2) {} }; Believe it or not, the code compiled with no errors/warnings and the assignments took place correctly! It was only when doing the final check before checking in my code when I realised what I had done. My question is: why did my code compile? Is something like that allowed in the C++ standard, or is it simply a case of the compiler being clever? In case you were wondering, I was using Visual Studio 2008 Thank you.

    Read the article

  • extraneous calls to copy-constructor and destructor

    - by eSKay
    [This question is a follow up to this question] class A { public: A() {cout<<"A Construction" <<endl;} A(A const& a){cout<<"A Copy Construction"<<endl;} ~A() {cout<<"A Destruction" <<endl;} }; int main() { { vector<A> t; t.push_back(A()); t.push_back(A()); // once more } } The output is: A Construction // 1 A Copy Construction // 1 A Destruction // 1 A Construction // 2 A Copy Construction // 2 A Copy Construction // WHY THIS? A Destruction // 2 A Destruction // deleting element from t A Destruction // deleting element from t A Destruction // WHY THIS?

    Read the article

  • F# constructor syntax - overiding and augmenting new

    - by Benjol
    I have a non-disposable class with Open/Close syntax that I'd like to be able to use, so I'm trying to inherit from it, and work the Open into the new and the Close into Dispose. The second part is ok, but I can't work out how to do the Open: type DisposableOpenCloseClass(openargs) = inherit OpenCloseClass() //do this.Open(openargs) <-- compiler no like interface IDisposable with member this.Dispose() = this.Close() (cf. this question which I asked a long time ago, but I can't join the dots to this one)

    Read the article

  • C++, constructor restrictions

    - by Pie86
    Hi everybaody, I'm studing C++ and I can't understand the meaning of the boldface sentence below: From IBM manual: The following restrictions apply to constructors and destructors: Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared static, const, or volatile. Unions cannot contain class objects that have constructors or destructors. Could you please provide me an example? Thank you!

    Read the article

  • Problem with default member functions of class in C++ (constructor, destructor, operator=, copy cons

    - by Narek
    We know that compiler generates some member functions for user-defined class if that member functions are not defined but used, isn't it. So I have this kind of code: class AA { }; void main() { AA a; AA b(a); a = b; } This code works fine. I mean no compiler error. But the following code.... class AA { int member1; int member2; }; But this code gives an run time error, because variable "a" is used without being iniltialized!!! So my question is this: when we instantiate an int, it has a value. So why the default constructer doesn't work and by using those two int numbers initializes variable "a"??

    Read the article

  • Using RhinoMocks, how do you mock or stub a concrete class without an empty constructor?

    - by Mark Rogers
    Mocking a concrete class with Rhino Mocks seems to work pretty easy when you have an empty constructor on a class: public class MyClass{ public MyClass() {} } But if I add a constructor that takes parameters and remove the one that doesn't take parameters: public class MyClass{ public MyClass(MyOtherClass instance) {} } I tend to get an exception: System.MissingMethodException : Can't find a constructor with matching arguments I've tried putting in nulls in my call to Mock or Stub, but it doesn't work. Can I create mocks or stubs of concrete classes with Rhino Mocks, or must I always supply (implicitly or explicitly) a parameter-less constructor?

    Read the article

  • Is it possible for an abstract class to force it's children to have a constructor in PHP?

    - by Logan Serman
    I would like to do something like this: abstract class Foo { public function __construct() { echo 'This is the parent constructor'; } abstract function __construct(); } class Bar extends Foo { // constructor is required as this class extends Foo public function __construct() { //call parent::__construct() if necessary echo 'This is the child constructor'; } } But I get a fatal error when doing this: Fatal error: Cannot redeclare Foo::__construct() in Foo.php on line 8 Is there another way to ensure child classes have a constructor?

    Read the article

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