FAQ Database Discussion Community


Does C have a shorthand way of initialize a struct with malloc and set its fields?

c,data-structures,struct,initialization,malloc
I have a messy block of code like result = (node*)malloc(sizeof(node)); result->fx = (char*)malloc(sizeof(char) * 2); result->fx[0]='x'; result->fx[1]='\0'; result->gx = NULL; result->op = NULL; result->hx = NULL; where I initialize an element of type typedef struct node { char * fx; // function struct node * gx; // left-hand side...

C++ Object Creation & Lists

c++,list,initialization
Main Method -> contains a list of Family objects. Family -> contains a list of Person objects. Upon creation of a Family object, how do I force it to create a new list of ‘Person’ objects for every new instance of Family?? Currently all Family objects in the main list...

Swift UIViewController Custom init() - Error cannot assign to self

ios,objective-c,swift,initialization
In Objective-C I used to override the init method of my UIViewController. I cannot achieve the same in Swift : Objective-C code : - (instancetype)init { self = [super init]; if (self) { self = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"ViewController"]; } return self; } If I try to do so...

Linux C++ Dynamic Libs and static initialization order

c++,linux,dynamic,initialization,shared-libraries
Forgive me on the long post. Its a complicate problem I wanted a complete description. On Linux Fedora 21 (g++ 4.9.2) and like. I'm working on a C++ database wrapper library using a base class of "database" and inherited classes of Oracle and Sybase. Beyond that, I wanted some of...

C++11 Uniform initialization for constructor and operator=

c++,c++11,initialization
I have T class and Table that uses T for construction parameter. struct T { string name; long value; }; class Table { public: T a, b, c; Table(T a, T b, T c) { cout << "From constructor: " << a.name << endl; this->a = a; this->b = b;...

PHP Why can't initialize static variable to time()?

static,initialization
I received error when set static variable initial value to time(). The error message is "syntax error, unexpected '(', expecting ',' or ';' in [...][...] on line 7" <?php define("DEBUG", true); define("NEWLINE", "<br>"); ... function debugMsg($msg) { static $lastTime = time(); if(DEBUG==true) echo date('Y-m-d H:i:s', time())." ".$msg." (".(time()-$lastTime)." seconds)".NEWLINE; $lastTime...

Fill immutable map with for loop upon creation

scala,dictionary,collections,initialization,immutability
I have this map that looks like this: val fields: Map[(Int, Int), Field] and I thought about doing something like: val fields: Map[(Int, Int), Field] = Map( for(a <- 0 to 10) { (0, a) -> new Field(this, 0, a) } ) instead of a long copy/paste list like: (0,...

F# declare variable without instatiating it

f#,scope,initialization,instantiation,declare
I need to declare a variable in F# without instantiating it. This is simple in C#, but in F#, all I have is the val keyword, and that only works within classes. Is there a way to declare a variable for scope purposes, but to leave the initialization for later?...

Is it conventional for Swift UIViewController implementations to use default property values, or to initialize properties in viewDidLoad?

swift,uiviewcontroller,initialization
In a Swift implementation of a UIViewController, we have the opportunity to use default property values instead of having to conduct the UIViewController initializer ceremony. For example: class ViewController: UIViewController { let model = SomeModelObject() What are the impacts of this approach, rather than instantiating the model property in, say,...

SAPUI5 Page Init/Re-Init

initialization,sapui5
I have a main screen with a tile the user can press to go to another page. The oninit: for this second page works fine in getting/setting the model and the data shows correctly. If I 'go back' to the first page (after I have made changes on the second...

intialization of structs/classes without constructors in stack vs heap

c++,struct,initialization
I would like to know the rule for zeroing-out structs (or classes) that have no default constructor in C++. In particular, it seems that if stored in the stack (say, as a local variable) they are uninitialized, but if allocated on the heap, they are zero-initialized (tested with GCC 4.9.1)....

Cannot Find Symbol Error with event handler

java,if-statement,scope,initialization,parseint
I am having trouble trying to initialize a variable correctly. Earlier I was getting a Number Format Exception because I was parsing an integer inside of an empty text field. Now I have created an if statement that checks first to see if the field is empty, then parses an...

Initialize char array in C

c,arrays,initialization
I am not sure what will be in the char array after initialization in the following way: char buf[5]={0,}; Is that equivalent to char buf[5]={0,0,0,0,0}; ...

Swift optional values during initialization preventing default initializer inheritance

swift,initialization,constants,optional,swift-playground
In Swift: 1) If you provide a default value for all of the stored properties in a class, then you inherit the default initializer, ie - init(). -- AND -- 2) A property of any optional type defaults to the value of nil, ie - var shouldBeNill: String? //should initially...

Android swipe: Initial tutorial in an app

android,initialization,swipe,slide
I'm trying to do an initial tutorial in my app like in this image: Do you know the name of this feature? In order to find a tutorial for it....

Can someone explain what is going on with this array?

java,arrays,initialization
I am quite confused on how my array is formed. This is what is written to make the array. public class TestProgram { public static final Room[] rooms = new Room[] { new Room ("GARDEN0001", "NorthWest Garden View", 45.00), new Room ("GARDEN0002", "SouthEast Garden View", 65.0), new Room ("GARDEN0003", "North...

Rails - initialize object instance variable

ruby-on-rails,initialization
I have two arrays which I would like to initialise to [] in my Prediction model's object. If I try: def initialize @first_estimation = [] @last_estimation = [] end Then many of my unit tests fail. Failure/Error: assign(:prediction, Prediction.new( ArgumentError: wrong number of arguments (1 for 0) However, if I...

NSUserDefaults key initialization when app starts for the first time

ios,swift,crash,initialization,nsuserdefaults
If I start an app for the first time, the boolean key for a NSUserDefaults is nil and the app crashes when it tries out the state of the setting in an if-statement. I try to initialize the key in viewDidLoad() as follows but the key seems to keep undefined:...

unexpected initialization of global variable

c,linux,pointers,gcc,initialization
I have the header file as: test.h //Mandatory fields size macro #define size_uid 65 #define size_txn 33 #define size_adhaarNo 13 #define size_ver 4 #define size_input 65 #define size_photo 1024*1024*10 #define size_pseudonym 50 #define size_name 50 //Mandatory fields declaration char uid[size_uid]; char txn[size_txn]; char adhaarNo[size_adhaarNo]; char ver [size_ver]; char *photo; char...

Anonymous Union in Struct Initializer

c,struct,initialization,unions
Why does following example not work in C? #include <stdio.h> typedef struct { int x; } X; typedef struct { char y[10]; } Y; typedef struct { int pos; union { X x; Y y; }; } Test; int main() { X x = { 65 }; Y y =...

Initialize Arraylist in method [duplicate]

java,methods,arraylist,initialization
This question already has an answer here: Is Java “pass-by-reference” or “pass-by-value”? 54 answers Following Question. I have a big amount of ArrayList attributes (basically the same as Kreuzlagerort20kg etc). Instead of initializing them all in the constructor (the part commented out) i'd love to initialize them inside the...

How smart is Java when detecting an uninitialized local variable?

java,initialization
I know Java forces you to initialize every local variable before you use it. There are some cases where it gets tricky, though. Consider this: public class TestClassOne { public void methodOne() { String s; if(false) System.err.println(s); else s = "Hi"; } } This class will compile succesfully. However, this...

Overwriting and custom inits in objective-c

ios,initialization,overwrite
I have a class that inherits the MPMoviePlayerViewController. I'm trying to rewrite the init method so that I don't have to repeat code for every other -initWithSomething function. For a custom initWithSomething method this will work. But I can't figure how to make it work for inherited iniWithSomething methods -(instancetype)init...

How to initialize bidirectional graph in Swift?

swift,initialization
I have some classes that create a graph with "back pointers". I tried to make the back pointers unowned (they'd create cycles otherwise) and initialize them in my init(), but that creates problems with self references. How am I supposed to get around this? class Parent { var child1:Child var...

Changing const member within class

c++,initialization,const,subclass
I would like to let a const int be changed by a function within a class. class Parent { int currentIndex; private: initMember(const int& member) { member = currentIndex++; } } class Child { const int Member1; const int Member2; Child () { initMember(Member1); initMember(Member2); } } Who ever writes...

Why using different (shared_ptr and normal) pointer constructors on the same class I get different results?

c++,c++11,constructor,initialization,default
Inspired by this question I wrote my own little program (using code from this answer) and discovered things that confused me. Namely: Having those classes: class A { public: A(){} int i; int j; }; class B { public: B() = default; int i; int j; }; I wrote 4...

difference between slice declaration and initialization

go,initialization,slice
What is the difference between a and b? I know that reflect.DeepEqual considers them not equal and I know that a is nil. Are there built in functions that easily show the difference? var a []foo b := []foo{} ...

In-class member initializer using a constructor: is it allowed? [duplicate]

c++,c++11,constructor,initialization,in-class-initialization
This question already has an answer here: Why C++11 in-class initializer cannot use parentheses? 2 answers I recently found an interesting piece of code in the article Get to Know the New C++11 Initialization Forms by Danny Kalev: class C { string s("abc"); double d=0; char * p {nullptr};...

Static template member array sizeof used in method

c++,arrays,templates,initialization
I have a template class with a static member array, and a method, which needs the size of the array. template <int i> struct Foo { static int data[]; static int size() { return sizeof(data) / sizeof(data[0]); } }; I want to initialize the array differently for each template specialization....

Why it is allowed to initialize static variable with non const here?

c,gcc,initialization,const,static-variables
I was reading this. The first answer by @Andrei T says that A "large" object is never a constant expression in C, even if the object is declared as const. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects...

proper __init__ definition in class inherited from “list”

python,python-3.x,initialization
I'm trying to define "the good way" an init function for my class inherited from list. Here is the very basic code (I've kept the necessary only): class measurementPoint(list) : """measurementPoint class : contains all the pairedMeasurement at a given temperature for a given channel""" def __init__(self, item): try: assert...

Why is there not any warning on a declaration without initialization in a for loop?

c++,initialization,g++,warnings,declaration
I tried to compile the following code using g++ (gcc version 4.8.2 (Debian 4.8.2-1)), with -Wall flag (adding the -Wextra flag does not change anything for me). #include <iostream> using namespace std ; int main() { int i ; cout << i << endl ; } It gave this warning:...

Is this aggregate initialization or default initialization in C++?

c++,initialization,aggregate-initialization
Consider following program. #include <iostream> int main() { int a=int{}; std::cout<<a; } Is it uses aggregate initialization or default initialization? I am confused....

Initializing a multidimensional array

c++,arrays,multidimensional-array,initialization
I am trying to initialize a multidimensional array in batches and can't seem to make it work or find an example! The dimensions I am working with are big enough that I don't want to specify them by hand! More precisely : int test[5][192]; for(int i = 0; i <...

Best practice to append value to an empty list [duplicate]

python,list,initialization
This question already has an answer here: why does python's list.append evaluate to false? 5 answers I'm just curious about the following code fragment not working, which should initialize an empty list and on-the-fly append an initial value. The second fragment is working. What's wrong with it? Is there...

iOS: How to make factory method work with subclassing

ios,objective-c,inheritance,initialization,subclassing
I have a class of type Matrix which I'd like to subclass. Let's call my subclass Column. I'd like to add new properties to my subclass as well. I love factory methods, and don't like to repeat code, so I create a factory method in my subclass which calls its...

Initial Population of Genetic Algorithm [closed]

matlab,initialization,genetic-algorithm,population
How to generate the chromosome which is x=[1 0;0 1;1 0;1 0] or [1 0;1 0;0 1;1 0] like this. I need to generate the chromosomes only with the help of "x=1 when ith machine is in cell l, otherwise 0 when i= no of machine and l= no of...

I do not why initialization is needed in this code in java

java,initialization
I do not know why the initialization of currentCard is needed there (where I commented in my code). Is that statement really needed in this code? public class Card { private String face; private String suit; public Card( String cardFace, String cardSuit ) { face = cardFace; suit = cardSuit;...

difference between character array and integer array

c,arrays,string,pointers,initialization
char *s = "Hello" char s[6] = "Hello" Any one of the above syntax would work fine. But what about following? int a[3] = {1,2,3} (this would work excellent) But why not this, int *a = {1, 2, 3};? Explanation along with the comparison between case [2] and [4]...

How can I initialize a record type in PL/SQL without null parameters

plsql,initialization,record
I have a record type like the following: CREATE OR REPLACE TYPE CUSTOM_REC_TYPE AS OBJECT ( ID NUMBER(19), COLUMN1 NUMBER(19), COLUMN2 NUMBER(19), COLUMN3 NUMBER(19), COLUMN4 NUMBER(19), ..... , ..... , ..... , ..... ) I need to initialize a record of this type. Using the following syntax: l_custom_rec := CUSTOM_REC_TYPE();...

sorting an array in the same line as instantiation/initialization

java,arrays,sorting,initialization
If given an array of ints: int[] age = new int [] {32, 25, 56, 56, 12, 20, 22, 19, 54, 22}; Is there a way to sort(lowest-highest) in the same line as instantiation/initialization, so that the elements of age would be: 12, 19, 20, 22...?...

Cannot reference a field before it is defined, but only if you don't qualify it [duplicate]

java,initialization,syntax-error
This question already has an answer here: Illegal forward Reference java issue 4 answers I found happening with the following code made my jaw drop: public class MCVE { { // instance initializer System.out.println(test); // cannot reference a field before it is defined System.out.println(this.test); } private final String test...

BluetoothAdapter.getDefaultAdapter(); returns null

android,bluetooth,initialization,adapter
I'm starting to develop an app to communicate with an arduino device through bluetooth. I'm initializing the bt adapter with BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); The problem is that btAdapter returns null, txt_status.append("\nAdapter " + btAdapter); Its like the device hasn't got a bluetooth adapter, which is not my case. Any...

How to best handle C++ object initialization: empty constructors or pointers?

c++,pointers,object,initialization,declaration
I'm wondering what is the best way to go about object initialization and storage with regards to objects that have to have a relatively large scope / long lifetime. Let's say we have a GameEngine class that needs to initialize and hold a reference to a Window for rendering. The...

PySide.QtGui RuntimeError: '__init__' method of object's base class not called …but it was

python,initialization,runtime-error,qtgui
Some environment basics Python Version: 3.4.2 OS: Windows 8.1 Searching so far, I suspect this other question is related to my issue at hand, but I'm not sure how I'm replicating enough of the same conditions--probably my lack of in-depth python knowledge. Simplified code to reproduce issue: Base Class from...

Initializing a Three Dimensional Vector in a C++ Class

c++,c++11,vector,initialization,init
Using the following code I would like to move a multidimensional vector in various directions. Unfortunately right after initializing I get an EXC_BAD_ACCESS error. Direction: Values from 0 to 2 for x,y and z movement Steps: Only -1 and 1 (Back, Forward) Container: Multidimensional Vector if (verMove(direction, steps)==true) { std::vector<int>...

how to initialize static array within struct

c,arrays,struct,initialization,static-array
I have this struct: typedef struct { int start; int end; char board[10][10]; } move; when I try initializing it this way: char new_board[10][10] move struct new_move = {0, 0, new_board} I get this error: warning C4047: 'initializing' : 'char' differs in levels of indirection from 'char (*)[10]' any suggestions?...

Object initialization with protocol and class name in swift

objective-c,swift,initialization,protocols
In Ojective-C I wrote: id <MyProtocol> object = [[NSClassFromString(@"aClassName") alloc] initWithObject:obj]; I would like to write this in Swift. Is there to do the same or am I out of the language paradigm ? edit : Here's my context. Somewhere I have : - (instancetype)initWithObject:(NSArray *)array andClassName:(NSString *)className { self...

brace initialization for specialized vector template

c++,templates,c++11,initialization,parameter-passing
I have this 3D vector template template <class TYPE, class VEC> class Vec3TYPE{ public: union{ struct{ TYPE x,y,z; }; struct{ TYPE a,b,c; }; TYPE array[3]; }; inline void set( const VEC& a ){ x=a.x; z=a.y; z=a.z; }; inline void add( const VEC& a ){ x+=a.x; z+=a.y; z+=a.z; }; // +...

Scala scope, initialization

java,scala,scope,initialization
Imagine the following Java Class: class Test { private Button b; private Table t; public Test() { setupButton(); setupTable(); } private void setupButton() { b = ... b.doAwesomeStuff(); // ... more stuff going on } private void setupTable() { t = ... t.attach(b); // Works, because b is in (class)...

Excel Visual Basic Run-time error '1004' when initializing a variable

excel,vba,excel-vba,initialization
I am learning visual basic and this script I'm using is coming up with an error when I am initializing the variable "i", i'm not sure what the problem is but I am getting the error message "Run-time error '1004': Application-defined or object-defined error" Here is my code: Sub excelmacro()...

F# initialize objects inside struct with constructor

class,struct,constructor,f#,initialization
I have the following struct in F#: type public Data = struct val class1: Class1 new() { class1 = new Class1() } end But I get an error that says structs cannot have an empty constructor. Class1 is a class that has a valid default constructor, and needs to be...

Why cppcheck tool does not find uninitialized variable?

c++,initialization,warnings,cppcheck
I run commad (Ubuntu 12.04) cppcheck test.cpp I am expecting uninitialized variable warning from cppcheck tool. Why cppcheck tool does not print it on the command line? Example cpp code: #include <iostream> class Foo { private: int m_nValue; public: Foo(); int GetValue() { return m_nValue; } }; Foo::Foo() { //...

Changing an element value in array does not reflect properly

c,arrays,string,initialization
I need to understand this for my computer science project but I am not sure what is going on, the code is #include <stdio.h> void main () { char x[6] = "12345\0"; char y[6] = "67890\0"; y[7]='A'; printf("X: %s\n",x); printf("Y: %s\n",y); } And the output is: X: 1A345 Y: 67890...

Python: Cleaner ways to initialize

python-2.7,initialization
Or maybe I should say, ways to skip having to initialize at all. I really hate that every time I want to do a simple count variable, I have to say, "hey python, this variable starts at 0." I want to be able to say count+=1and have it instantly know...

static member variable initializing twice

c++,static,initialization
I'm using my own REGISTER_OBJECT() macro to create a factory full of classes. It works as expected, except for the initialization of my static std::map variable. If I don't initialize the static std::map in a .cpp file, I'll of course get a unresolved external symbol. But the problem is, I...

Golang - structs, intializing and memcpy - what is the proper way?

arrays,struct,go,initialization,custom-type
I'm new to Go and I wish to translate some C/C++ code I have to Go but I haven't been able to. The problem resides in 2 places: how can I initialize a struct I've defined and how to do a "memcopy" The code I'm talking about is this: http://play.golang.org/p/e8N255qEAk...

Are () and {} always equivalent when used for initialization with “new”?

c++,c++11,constructor,initialization,new-operator
There is a post that deals with parentheses or not after the type name when using new. But what about this: If 'Test' is an ordinary class, is there any difference between: Test* test = new Test(); // and Test* test = new Test{}; Furthermore, suppose Test2 has a constructor...

Object initialization (Java)

java,class,object,methods,initialization
Say you have a class called team: public class Team { public void Team() { Player player1 = new Player(); Player player2 = new Player(); if (player1.getName == "") { player1.setName = console.next(); } else if (player2.getName == "") { player2.setName = console.next(); } } } And another class called...

Initialization of a union in C

c,initialization,unions
I came across this objective question on the C programming language. The output for the following code is supposed to be 0 2, but I don't understand why. Please explain the initialization process. Here's the code: #include <stdio.h> int main() { union a { int x; char y[2]; }; union...

Initializing a property through the private attribute

objective-c,initialization
I'm learning Objective-C with the Big Nerd Ranch Guide. The author uses a store from which the controller can get some data to display : #import "BNRItemStore.h" #import "BNRItem.h" @interface BNRItemStore () @property(nonatomic) NSMutableArray *privateItems; @end @implementation BNRItemStore +(instancetype)sharedStore { static BNRItemStore *sharedStore = nil; if (!sharedStore){ sharedStore = [[BNRItemStore...

Why doesn't Swift force my designated initializer to call super?

swift,initialization,nsobject
This code is legal in Swift: class Snapper : NSObject { var anim : UIDynamicAnimator init(referenceView:UIView) { self.anim = UIDynamicAnimator(referenceView:referenceView) // super.init() } } Observe that in my initializer I didn't call super.init(); I commented out that line. But the Swift compiler doesn't complain. Why? I thought there was a...

clarification of initialization in C++

c++,initialization,uniform-initialization
I am really getting confused in following examples: #include <iostream> class C { public: int a,b; }; int main() { C c{3,6}; std::cout<<c.a<<'\n'; std::cout<<c.b<<'\n'; return 0; } It works fine and gives the expected outcome. But if I modify the above code like below. #include <iostream> class C { int...

Zero initialize multidimentional array in class constructor C++

c++,c++11,multidimensional-array,constructor,initialization
Is there a way (with C++11) to zero-initialize a multidimensional array in a class constructor? Does this initialize the whole array to zero or just the first dimension? class Example { public: int array[100][100]; Example():array{} { }; }; Lastly, will this work with enumerated types?...

Overlapped data when amend values of variables in shell script ubuntu 9.04 for ARM

shell,initialization,ubuntu-9.04
I created shell script in /etc/init.d/ to start stop my application. The script based on skeleton script file which originally located in /etc/init.d. This script imports variable from xxx.conf configuration file. # Read configuration variable file if it is present [ -r /etc/xxx.conf ] && . /etc/xxx.conf When doing assign...

Does C language specify any implicit initialization for void pointers only?

c,pointers,initialization,language-lawyer,void-pointers
Here is my code: int main() { int *p; void *x; printf("%p\n", p); printf("%p\n", x); return 0; } which will print: koraytugay$ ./a.out 0x7fff53b35ad0 0x0 koraytugay$ ./a.out 0x7fff5803fad0 0x0 koraytugay$ ./a.out 0x7fff512c9ad0 0x0 koraytugay$ ./a.out 0x7fff55213ad0 0x0 koraytugay$ ./a.out 0x7fff52dbdad0 0x0 Is there any explanation to this behaviour in the...

does enum fields have default values in c language

c,enums,initialization,language-lawyer
I'm reading a c code somewhere, I found this structure typedef enum { SPIIP_0, SPIIP_1, NUMBER_OF_SPIIP, ERROR_SPIIP }SPIIP_ID_E; and somewhere else in my code I found statemment : if(IP>NUMBER_OF_SPIIP) but NUMBER_OF_SPIIP value is declared nowhere my quesion is : deos enum type define value to it's elements ...

Data stored in different lines on a file, how to load them as parameters to a class?

java,initialization,bufferedreader,readline
I'm trying to do a small sentence translator, each sentence has one or more translations that will be loaded from a file formatted like this: EN – english sentence 1 IT – italian translation 1 EN – english sentence 2 IT – italian translation 1 IT – italian translation 2...

fill_n() is not letting change variable value

c++,arrays,initialization
I am using fill_n() function to initialize my array values, but then I cannot change the values of the array, it is always the initial value. Can someone explain me why is that? #include<iostream> #include<ctime> int main(){ //Matrix int m[3][3] = {{1,0,0},{0,1,0},{0,0,1}}; int v[3] = {5,6,7}; int result[3];// = {0,0,0};...

Initializing ZeroMQ 2.2 message in “almost always auto” style wants to use private constructor

c++,c++11,constructor,initialization,zeromq
I have written a C++11 program which uses ZeroMQ. In one particular line I want to create a new message as a local variable and initialize it with the size of a vector called serialized, using the "almost always auto"-style syntax: auto zm = zmq::message_t {serialized.size()}; This compiles fine on...

Java variable visibitlity

java,variables,scope,initialization,disambiguation
I have the following code: public class Java0102 { public static void main(String[] args) { int x = 2; int y = 10; if (x == 2) { x = 5; int w = y * x; } System.out.println("W="+w); int W = x*y*w; y = x; System.out.println("New W="+w); System.out.println("X="+x); System.out.println("Y="+y);...

Declare Two-Dimensional Array - Clarification

java,arrays,multidimensional-array,initialization,declare
I am currently taking Java lessons, and the course is explaining two-dimensional arrays. The first method to declaring that type of variable would be to create a constant as arguments for how many rows and columns will be in my two-dimensional array. Then, I just used a nested for-loop to...

How do I un-initialize an object in C++?

c++,class,object,initialization
I'm not 100% certain I worded the title for this right so here's what I want to be able to do... I have a class that gets defined like so... class Animal { public: Animal() : m_name("New Animal") { } Animal(const std::string& name) : m_name(name) { } Animal(const Animal& animal)...

ruby: calling super without having a parent class

ruby,initialization,parent,super
I have a class which overrides self.new and calls super in it, but the class doesn't derive from antoher class. So what exactly does the call? class Test attr_reader :blatt def self.new(blatt, quellformat, &block) begin # why can't I call initialize(blatt,quellformat) here? # when I try this, it only prints...

Why is direct-list-initialization with auto considered bad or not preferred?

c++,c++11,initialization,auto,type-deduction
I've come into the habit of writing code with direct-list-initialization like below as it's more effective and it's very useful to prevent implicit narrowing: int i {0}; string s {""}; char c {'a'}; bool b {false}; auto num {100}; // But this?? But when it comes to the auto specifier,...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int
void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

Using derived class members for the initialization of the parent class

c++,initialization,derived-class,initializer-list
I would like to initialize a class B that's derived from class A, and where in B I construct a cache first that is used with the construction of A, e.g., class B: public A { public: B(): A(cache_), cache_(this->buildCache_()) protected: const SomeDataType cache_; private: SomeDataType buildCache_() const { //...

how to initialize the “min” variable properly?

c,gcc,initialization
I have a small problem in my code for finding the minimum value from a series of numbers. When I initialize min = 0, the minimum value turns out as 0. But when I don't initialize min, the answer is correct! Why does this happen? Xcode tells me I should...

Difference between the different ways to initialize std::string

c++,string,initialization
Lately I have been seeing quite a few people who initialize their std::strings like this: std::string a{ "test" }; // Yes they do it with a single value Now I wouldn't use this unless it's an array or to pass an initialization list. But it got me curious, is there...

Java check if a boolean is initialized

java,initialization,boolean
I'm not talking about checking if a boolean is null as a means to check if it is initialized. Because that won't work. So I thought this might work: public class MyClass{ private boolean setting; private boolean getSetting{ // get the setting; } public void main{ if (setting != (true...

Define size of vector of vector of vector at the time of declaration

c++,vector,initialization,size
Recently i had a chance to use vector<vector<vector<Some_Struct>>> threeFoldVec, We had to push this into a list. The size threeFoldVec is known at the time of initialization. I am aware of how to define size of 2_fold vector at the time of declaration. std::vector<std::vector<SomeStruct>> Layer_1(10, std::vector<SomeStruct>(5)); But when it comes...

Might not have been initialized error at null check

java,initialization,final
I'm checking if the variable is initialized but at that point netbeans is giving me variable reader might not have been initialized warning. How do I fix/suppress this? This is my code (summary): final Reader reader; try { reader = new Reader(directory); //additional stuff that can cause an exception }...

How to get Spring to execute a method when the bean is initialized?

java,spring,spring-mvc,initialization,postconstruct
I’m using Spring 3.2.11.RELEASE. I have a class (annotated with @Service), in which I have a method package org.mainco.subco.myproject.service; … @PostConstruct public void initCaches() { LOG.info("initiating caches."); … } // initCaches However, this method is never getting called, despite the fact the service class is included in a <context:component-scan />....

want to declare arrays by using constructor with variables

c++,arrays,constructor,initialization,destructor
class matrix { public: matrix(); matrix(int row, int column); ~matrix(); private: const int DEFAULT_SIZE; int size_row, size_column; double *entry; }; // main function int main() { //make a matrix of default size matrix A; /* no error */ delete A; //make 5 matrices of default size matrix *B = new...

Initialize filtered items in Isotope

filter,initialization,jquery-isotope
I have a problem with Isotope plugin (jQuery). I want to initialize plugin with already filtered items. I have seen some post on this topic, but answers were not clear. This is my code: <div class="filters"> <div class="ui-group"> <div class="button-group js-radio-button-group" data-filter-group="gender"> <button class="button is-checked" data-filter="">BOTH</button> <button class="button" data-filter=".female">FEMALE</button> <button...

Cannot implicitly convert Lazy to Lazy

c#,interface,initialization,lazy-initialization
I am coding a MVC 5 internet application and I have a question in regards to using an interface with Lazy<T> initialization. Here is the class definition in question: public class WebAPITokenService1_0 : IWebApiTokenService Here is my code that works with out using the interface in the declaration: Declaration: Lazy<WebAPITokenService1_0>...

Is it necessary to Initialize / Declare variable in PHP?

php,variables,initialization,declaration
This question's purpose is to only gain knowledge or information for me and many like me. So my question is: Is it necessary to Initialize / Declare a variable before a loop or a function? Asking this question is for my confusion because whether I initialize / declare variable before...

How to initialise global cell reference variables correctly in VBA

excel,vba,excel-vba,initialization,global-variables
In my VBA project I have a number of cells which I refer to within many modules and subs. For ease of reading sake I have declared and initialised a variable to the cell reference in the following way: LowerBound = ThisWorkbook.Sheets("Rules").Range("B22").Value I would like to initialize this variable just...

Pre-constructor initialization

c++,constructor,initialization
My problem is like this, I have a class named "Product" and another class named "Agriculture", the "Agriculture" class is inheriting the "Product" class. When I summon the "Agriculture" constructor obviously the "Product" constructor is summoned first. The question is, can I initialize one of the product's members via a...

When should we use / not use initialization in Java?

java,initialization
Why is int face; not initialized in this code? And when I should use or not use initialization? import java.util.Random; public class RandomIntegers { public static void main( String[] args ) { Random randomNumbers = new Random( 3 ); int face; for( int counter = 1; counter <=20; counter++) {...

Initialization in list - default value

c++,initialization
I've got this code sample: #include <iostream> using namespace std; class Polygon { private: double _Field; public: Polygon(): _Field(){} void show_field(){ cout << _Field << endl; } }; int main() { Polygon P1; P1.show_field(); return 0; } I'm just wondering why does show() method always shows me 0 value? Does...

Warning when trying to initialize a 2D struct array with two initializer lists

c,arrays,multidimensional-array,initialization,compiler-warnings
I am trying to initialize a 2D array of user defined type to zero by using following line, qmf_t X_hybrid_left[32][32] = {{0}}; Where qmf_t is a user defined type. Here I get the compiler warning, warning: missing braces around initializer [-Wmissing-braces]" But if I use, qmf_t X_hybrid_left[32][32] = {{{0}}};, i.e....

C++11: () or {} in List-initialization? [duplicate]

c++,c++11,vector,initialization,list-initialization
This question already has an answer here: Why does 'std::vector<int> b{2};' create a 1-element vector, and not a 2-element one? 3 answers I am referring to "The working draft N3337", which is said most similar to the published C++11 standard. If there are matchable constructors, then it call constructors....

Difference between methods to create a character array

c,arrays,string,initialization
I am curious about the different methods to create a character array in C. Let's say we want to create a character array holding the string "John Smith". We could either initialize the array by supplying the number of elements explicitly, i.e. char entireName[11] = "John Smith"; where there are...

C++ for loop variable lifetime is weird

c++,variables,scope,initialization,lifetime
for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { int n; n++; printf("n : %d\n", n)' } } The output of the code is 1 2 3 4 5 6 7 8 9. I'm wondering why the variable n in the...

Why use required Initializers in Swift classes?

swift,initialization
I am trying to understand the use of the required keyword in Swift classes. class SomeClass { required init() { // initializer implementation goes here } } required doesn't force me to implement the method in my child-class. If I want to override the required designated initializer of my parent...

What's the difference between Obj x = Obj(n) and Obj x(n) in c++? [duplicate]

c++,constructor,initialization
This question already has an answer here: Is there a difference in C++ between copy initialization and direct initialization? 7 answers I can't seem to find anything online about the differences between these two. Almost every teaching source online (learncpp.com, cplusplus.com etc) seem to all use Obj x(n); to...

PHP :Initializing elements of session array

php,arrays,session,initialization
I have created a session array as $_SESSION[yans]=array(); I wish to initialize first 5 elements of this to 0.How it can be done?

Initialize array of structures

c,arrays,dynamic,struct,initialization
I am having trouble initializing an array of structures in C. Here is my structure : typedef struct Voie { int num; int sem_num[3]; int crois[3]; } Voie; The two arrays will contain 0, 2 or 3 integers. I have an array of 12 "Voie" : Voie voies[12]; And I...

how to initialize a parameter in javascript function when i define the function

javascript,parameters,initialization,arguments
i have a defined a function with a parameter in javascript, and i don't know how to initialize it's parameter, any one help me. the code is bellow <br/>Enter a number: <input type="text" id="txt1" name="text1"> <p>Click the button to see the result</p> <button onclick="myFunction(5)">show result</button> <br/> <p id="demo"></p> <script> function...