FAQ Database Discussion Community


Why does adding a parameterless constructor to my entity model class work here? What are the implications?

c#,entity-framework,generics,constructor
So I have this office entity class: [Table("office_entity")] public class EFOffice : EFBusinessEntity { [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessName { get; set; } public virtual ICollection<EFEmployee> Employees { get; set; } public EFOffice(Guid id, Guid tenantId, string address, string businessName) {...

PHP get value from function called by constructor

php,class,constructor
I have a feeling I'm overlooking something simple but I can't figure out how to get a value from a function that is called by the constructor within my class. The below is a very simple example but, essentially, I need to use the userId value on my index.php page...

Omitting prototype.constructor changes prototype chain

javascript,constructor
I'm trying to understand inheritance in JavaScript and I've seen that in JavaScript there are different ways to accomplish inheritance. One such way is based off of an example from the Mozilla site which does something similar to the code below: function Person(name) { this.name = name; } Person.prototype.getName =...

Constructors in Julia: initializing named fields based on the input value of other named fields

constructor,julia-lang,compositetype
Imagine a constructor that takes two arguments and initializes 3 named fields using the values of the two arguments. Something like this: type test1 a b c test1(a,b) = new(a,b,a/b) end This works fine, but what if the value for c is not such a simple expression? What if it...

C++ why copy c'tor not called

c++,constructor,copy
Hey guys i have this code Animal.h: /* * Animal.h * * Created on: May 27, 2015 * Author: saif */ #ifndef ANIMAL_H_ #define ANIMAL_H_ #include <iostream> using namespace std; class Animal { int age; public: Animal(); Animal(const Animal & rhs); Animal addTo(); virtual ~Animal(); }; #endif /* ANIMAL_H_ */...

cannot reference before supertype has been called java

java,constructor,instance
I have a class Ship public class Ship { private String name; private boolean loaded; private int size; private boolean bIsDefeated; private int gunpower; public Ship(int size, int gunpower, String name) { this.size = size; this.gunpower = gunpower; this.name= name; loaded = true; bIsDefeated = false; } } and Submarine...

Can anyone explain why this snippet of code is working in the constructor only?

java,android,object,constructor
im a beginner in Java as well as Android development, who recently took up the task of developing a simple Android application however i recently faced a problem which i was able to resolve through trial and error. As i cant figure out the exact reason for this behavior, Can...

Constructor and const reference

c++,constructor,nodes,copy-constructor,const-reference
I;m study C++ right now (started like 2 days ago) and I have some trouble with writing Copy C'tor of Node. Node is a class as following: template <class T> class Node { T* data; Node<T>* next; friend class Iterator<T>; public: Node():data(NULL),next(NULL){} Node(const T& data):data(NULL),next(NULL){ T* copy = new T(data);...

c# how to give constructor fields from another class

c#,class,constructor
I have 3 Classes : Masina (Car), Destinatie (Destination) and MasinaDestinatie (CarDestination). I need the third class to get the values of the car number _nr_masina and the destination _cod_dest through it's own constructor. I need to make a constructor with parameters in the third class that stores the values...

node creating instances via costructors

javascript,node.js,class,constructor,instance
While experimenting with nodejs I encountered a problem of enabling isntances creation via Constructors. I create simple cart basket functionality. I got file cart.js var items = []; function addItem (name, price) { items.push({ name: name, price: price }); } exports.total = function () { return items.reduce(function (a,b) { return...

Which is better programming practice - Unnecessary parameters or a static variable?

c#,parameters,constructor,static,xna
I am making a game in C# and XNA 4.0 and one of my classes requires its own texture. The class is currently being used like this: Class constructor: class Item : ItemBase //It uses a base class { public Item(Texture2D myTexture) : base(myTexure) { } } New instance: Texture2D...

Can we create a non parameterized constructor in servlet?

java,servlets,constructor
What I know till now: Instance of Servlet is first created by container via reflection and no argument constructor gets used. Then parameterized init method gets called. Also it is suggested that we should not create a constructor in servlet class as it is of no use. And I agree...

what does DefaultEdge.class mean in jgrapht example

java,parameters,constructor,jgrapht
What does dot class mean in the parameter passed to Constructor I am using jgrapht for the first time . I have this question What are we passing to the constructor of the DefaultDirectedGraph class? I mean what does DefaultEdge.class means ? There is no static field with that name...

Java : recursive constructor call and stackoverflow error

java,recursion,constructor
Please help to understand why does the following code public class HeapQn1 { /** * @param args */ public HeapQn1() { new HeapQn1(); } static HeapQn1 n = new HeapQn1(); public static void main(String[] args) { } } results in java.lang.StackOverflowError at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:8) at com.rg.test.interview.HeapQn1.<init>(HeapQn1.java:9) ... As per my understanding...

Any Example that Prove Initializer List Call before Constructor C++

c++,constructor
I have searched but still didn't get easy and proper answer, Below is my code. #include <iostream> using namespace std; class Parent { private: int a; public: Parent():a(3) { cout << a; } }; int main() { Parent obj; return 0; } Can you add additional lines of code that...

Declarations inside a constructor in Java

java,constructor
Is the following accepted in Java ? I know it compiles, but is it accepted in Java, or should I change the code to something else ? Thanks ! public class Line extends Shape { public Line(int x1, int x2, int y1, int y2, Color myColor) { super(x1, x2, y1,...

When and how to default-initialize a const variable?

c++,c++11,constructor,default-constructor
clang++ does not ever allow default initialization of a const variable of class-type without a user-defined constructor; g++ is slightly less restrictive (see below). According to this answer, this is because POD types "are not initialized by default." If I understand correctly, this means that default-initialization does not invoke the...

constructor and templates

c++,templates,constructor
I was going through this piece of code where I came across a while calling this code from main #include <iostream> #include <vector> using namespace std; class abc { public: enum example { a=1, b=2, c=3, d=4 }; }; template<typename T> class xyz { public: xyz(T &v,abc::example ex=abc::a):b(v),len(sizeof(T)) { }...

How to accumulate a value in java?

java,class,constructor,instance,accumulator
Right now, I'm learning all about class, constructors and instances. I've made a small bit of code in java and I'm stuck with this particular code. ***MY CODE OUTPUT IS SUPPOSE TO BE LIKE THIS: OUTPUT Enter amount:500 Do you want to enter amount again?(y/n):y Enter amount:45 Do you want...

Javascript: is calling a method/function within a constructor function allowed?

javascript,constructor
I was wondering if its allowed in JavaScript to call functions or methods in the process of constructing objects with a constructor function since its job is just to create objects. Example: function Animal(name) { this.name = name; alert("I am called in the constructor-function. Is it allowed?"); } var x...

Why I obtain this error message when from a class I try to create a new instance of another class calling its constructor? [closed]

java,constructor
I have this problem trying to create a new object in Java. So I have a "test" class named TestLoadFatturePa, this one: package it.sistinf.ediwea.fepa; import java.util.Vector; public class TestLoadFatturePa { /** * Avvia l'applicazione. * @param args un array di argomenti della riga comandi */ public static void main(java.lang.String[] args)...

Throwable constructors

java,exception,constructor,throwable
The 4 types of Throwable constructors are :- Throwable() : Constructs a new throwable with null as its detail message. Throwable(String message) : Constructs a new throwable with the specified detail message. Throwable(String message, Throwable cause) : Constructs a new throwable with the specified detail message and cause. Throwable(Throwable cause)...

Contructor call error message [duplicate]

java,constructor
This question already has an answer here: Why does this() and super() have to be the first statement in a constructor? 11 answers Any ideas why I may be seeing the following message for this class? package org.swx.nursing.tools.sqlfinder.gui; import javax.swing.JPanel; import java.awt.event.ActionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class...

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 constructor reference assignment Vs new created object assignment

java,constructor,java-8,variable-assignment,method-reference
I met in our project following code: MyInterface var = MyClass::new; Is there difference with MyInterface var = new MyClass(); Lazy?...

Why it is not suggested to pass hardcoded absolute path name to File object constructor File(String)

java,file,constructor,static-analysis,hardcoded
I am creating a File object in Java using File(String pathName), where pathName is the absolute path to the file. While this works perfectly fine from functionality point of view, but it frequently ends up as an static analysis defect. Is there any specific reason why it is suggested to...

Functions with pointer arguments in C++

c++,function,pointers,constructor,ampersand
I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running: #include <iostream> using namespace std; class Item { public: Item(Item * it) { data = it->data; } Item(int d) { data = d; } void printData() { cout << data << endl;...

Class has no member “Class”

c++,constructor
I am trying to create a class called Drone, and have two files, Drone.h and Drone.cpp. Drone.h class Drone { protected: void foo(); }; Drone.cpp #include "Drone.h" Drone::Drone() // <---ERROR { } void Drone::foo() { } I get the error: "Class 'Drone' has no member Drone." in the tooltip as...

Javascript constructor function to count the number of instances

javascript,object,constructor,count
Okay, so I want to create a constructor function in javascript which will count the total number of instances which are created using this constructor. var Component = function(name) { this.name = name; this.add = function(){this.prototype.countInstances++;}; this.add(); }; and Component.prototype.countInstances=0; As I understand it correctly, the countInstances variable is added...

How to parameterize the number of parameters of a constructor?

c++,templates,c++11,constructor
I want to accept up to a number of parameters (this number being defined in a template parameter) in a template class constructor. I can't use an initializer_list, since I can't assert its size at compile time, as far as I know. What I tried My first attempt was using...

Invoking overload constructor within constructor

c++,constructor,operator-overloading
I was wondering either it is possible in c++ to run a constructor overload within another constructor. I know it is possible using regular methods. What I am tryng to do: class Foo { public: Foo(); Foo(int val); }; Foo::Foo() { Foo(1); } Foo:Foo(int val) { std::cout << val; }...

java - How to retrieve anything inside method

java,methods,constructor,local-variables,bcel
From what i know, java cannot retrieve anything inside method. so i using option -g or -g:vars in javac. for e.g : class Test { int a=0; void method(boolean boo){ String b; try { new Thread().sleep(1000); } catch(InterruptedException e){} JOptionPane.showMessageDialog(null,"test"); BufferedImage image=ImageIO.read(new File("C:\\file.png")); } } So, i use BCEL to...

int a=int(); what happens in C++98?

c++,constructor,c++98,built-in-types
Please read the question entirely before you think to mark it as duplicate. The statement like int i=int(); most programmers will say that there is value initialization here & i will be value initialized. (0 as output). But it also prints 0 as output on C++98 compiler. Following program that...

java: using default constructors in calculations

java,constructor
I have to write a program using constructors which calculates the area of a circle using 5 methods: Circle: The constructor that creates a circle with radius = 1 setRadius: takes an double argument and sets the radius to the argument getRadius: returns an double argument with the value of...

Understanding prototype object creation with 'Object.create()' instead of 'new' keyword

javascript,object,constructor,prototype
I came to a code that contains these lines var data = function() { function Metadata() { /*some initialization here*/ } Metadata.prototype = Object.create(Backend.prototype); Metadata.prototype.constructor = Metadata; return Metadata; } I struggle to understand what is actually going on, and how to use the returning object. If I understand it...

Redefinition using Constructor

c++,constructor,redefinition
I cant understand why I have redefinition trying to run this example. Can anyone tell me? using namespace std; class Base { protected: int *value; public: Base() { value = new int, *value = 1; }; Base(int &n) { value = new int[n]; } }; int main() { int x=2;...

Which way of setting fields value is better and why?

java,optimization,constructor
This question can be stupid, but I just want to know, is there any difference? class A{ // common code private int field; public void setField(int field){ this.field = field; } //way 1 public A(int field){ this.field = field; } //way 2 public A(int field){ setField(field); } } ...

Constructor and copy-constructor for class containing union with non-trivial members

c++,c++11,constructor,c++14,unions
I am trying to implement a custom variant type which uses a union to store data of various different types. In the field type_id I plan to store which type the data stored in the union is of. The union contains non-trivial members. Here is my current implementation: struct MyVariant...

Non-const copy constructor

c++,constructor,const,copy-constructor,observers
I'm doing copy on write optimization for object (i.e. when calling a copy-constructor just save pointer to an object and really copy it only if we need to change our object, or if object we are pointing to going to change). Before changing our object we need to notify others...

Creation of object using abstraction fails, likely a simple fix I cannot see

java,object,constructor,abstraction
A novice question about abstraction and constructors. I feel like I'm missing something obvious. I have an abstract class Piece, this is the constructor: public abstract class Piece { private int[] location = new int[2]; private final char color; public Piece(char color, int[] location) { this.location = location; this.color =...

Object declaration in C++

c++,object,constructor
I have two questions about the following code in c++. What does the line A obj() in main() mean? Its not giving any error. And why does the next line obj.fun(); give the following error? request for member 'fun' in 'obj', which is of non-class type 'A()' The code is:...

How can I access the members of a subclass from a superclass with a different constructor?

c++,inheritance,constructor,subclass,superclass
I have the following class and typedef: class Object { protected: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<string, Object> obj_map; And then I have its child: class Image: public Object { private: path full_path; int x; int y; img image; public: Image(path p, int...

Java call a method before constructor

java,methods,constructor,call
I have the class Map with a method setMapName which choose from an Enum mapName to set it, inside the constructor there is a rule to name a cell from the array sector either Alien or Human according to the mapName value, i want to test if the name of...

How to create my own object properly out of stdClass object

php,constructor,dynamic-binding
I'm creating instance of person according to data that i get from API response. The data returns as \stdClass and i want to convert it to my own object. Is there a way to pass all the calls in the constructor and make something more elegant? Class Person { protected...

Why does float argument fit to int function parameter?

c++,constructor,type-conversion
Please, look at this code: #include <iostream> class A { public: int my; A(int a=0) : my(a) { } }; int main() { A x = 7; // 1 A y = 6.7; // 2 std::cout << x.my << " " << y.my << "\n"; } It actually compiles although...

Constructing priority_queue instance with Compare instance of different type

c++,gcc,constructor,containers
Could anybody please explain why my compiler (GCC) accepts the code below as valid? priority_queue<int, deque<int>, less<int>> pq(greater<int>()); I expect this constructor (for an instance of type having less<int> as Comparator, as specified for priority_queue instance pq) to be incompatible with an instance of greater<int> (passed as constructor parameter), which...

Smart pointers when dealing with constructors

c++,constructor,smart-pointers
This question is in regards to my program. I was earlier using Manual Management using pointers, and now I'm trying to move to smart pointers (for all the good reasons). In normal pointers, it was easy to call a constructor of a class by using the new keyword. Like in...

Explicit instantiation of class template not instantiating constructor

c++,templates,constructor,explicit-instantiation
I'm working on a project in C++ and am having trouble understanding what members of a template class get explicitly instantiated when I explicitly instantiate the template class. I've written the following file, which I then compile using Visual C++ 2008 Express Edition's Release configuration and then pop into a...

Switching Classes during __construct()

php,class,oop,constructor,magic-methods
Let's take the following classes for a moment: class member { public $id; public function __construct($id) { $this->id = $id; // Check user level if ($this->check_user_level() == moderator) { $this = new moderator($this->id); } } private function check_user_level() { // Return user level from system based on user ID }...

Multiple constructor inheritance

c++,inheritance,constructor
I'm trying to make two smaller constructors that can be called on their own, then make one larger constructor which allows you to do everything at once by simply calling the two other constructors. Example of my code: Foo::Foo(bool someVar, int someOtherVar, int fooBar) : Foo(someOtherVar, fooBar), Foo(someVar) {} Foo::Foo(bool...

Different constructor in template: one for string and one for anything else

c++,string,templates,constructor
#include <iostream> #include <string> using namespace std; template <class Type> class Matrix { public: Type matrix[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (typeid(matrix[0][0]).name() == typeid(string).name()) { matrix[i][j] = "0"; } else { matrix[i][j] = 0;...

Construct an object, pass it to the base class constructor keeping control of its lifetime

c++,constructor
I need to derive a class Child from the class Base with the following requirements: Class Base constructor accepts a reference to an object of class Foo. Objects of class Foo should have same lifetime as an object of class Child. Constructors of Foo, Child and Base can throw, code...

How to avoid calling a too much parameterized constructor, with virtual inheritance?

c++,constructor,virtual-inheritance,method-signature
I want to perform a virtual inheritance with the following obvious example : class A { public: A(int a) : m_a(a) {} private: int m_a; }; class B : virtual public A { public: B(int a, int b) : A(a), m_b(b) {} private: int m_b; }; class C : virtual...

why I can't using new() to pass the parameter? [closed]

c#,vb.net,constructor
Move from VB to C# in VB I allowed to make like this SomeFunct(new someClass(param1, param2)) so tried it in C#, I got the error: Error 1 'someClass' does not contain a constructor that takes 2 arguments C:\Users..... why I can't do it in C#? I don't want create new...

Java Constructor Injection

java,constructor,dependency-injection,instantiation,constructor-injection
Let's say I have a class resources which instantiates all of my OpenGL / Java game objects and I then pass these via constructor to my Scene class (which requires them), like so (simplified example)..... public class Resources { Hero hero; Enemy enemy; MenuButtons mainMenuButtons; Background background; Scene mainMenu; public...

Laravel 5: How to add Auth::user()->id through the constructor ?

authentication,laravel,constructor
I can get the ID of the authenticated user like this: Auth::user()->id = $id; Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in...

How to gain Static Constructor's functionality in JAVA?

java,constructor,static,static-constructor
I am learning C# and JAVA I found Static Constructor in C# which is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. For...

How to pass the instance itself to an external map at the moment of its creation?

c++,dictionary,constructor,instance
I have a class Object and a typedef: class Object { private: long int id; public: Object(void); ~Object(void) {}; long int get_id(void); }; typedef map<long int, Object> obj_map; And then I have this class App, which has an obj_map and object_counter: class App { public: static ALLEGRO_DISPLAY *display; static ALLEGRO_EVENT_QUEUE...

How to make deep copy?

c++,arrays,class,constructor
VehicleRegistry::VehicleRegistry(){ vehicles = new Vehicle[4]; numvehicles = 0; maxsize = 0; } VehicleRegistry::VehicleRegistry(const VehicleRegistry& vr){ } How to make deep copy of that dynamic array?...

PHP > 5.4: overriding constructor with different signature

php,oop,constructor
We know that PHP doesn't accept child methods with a different signature than the parent. I thought that was the same with constructors: The PHP documentation states that This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ. However, it appears that inherited constructors still...

Having issues with methods

java,oop,methods,constructor
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem. Below...

How does a constructor choose a base class constructor in C++

c++,constructor
If you are inside the constructor of a derived class, and you make no explicit call to the base class constructor, how does the compiler know which base constructor to use?

Matlab - Constructor doesn't initliaize member values

matlab,variables,interface,constructor
Dear lovely community, I already looked in Google and in the forum and also found some interesting posts. But in the end I still didn't get it worked. So, I am going to post the question here. I know in Matlab are already get/ Set methods implemented, but I am...

Cannot understand templates and constructor-related error

c++,templates,inheritance,constructor
#include <iostream> #include <vector> #include <string> using namespace std; enum class demo_initialize { a = 1, b, c, d }; class Base { public: Base(demo_initialize initialize) : mInitialize(initialize) {} protected: demo_initialize mInitialize; }; template <typename T> class Derived : public Base { public: Derived(T &value, demo_initialize initialize = demo_initialize::a) :...

Can “new” be used inside the constructor of the class to call another constructor in Java?

java,constructor
I know that this(...) is used to call one constructor of a class from another constructor. But can we use new for the same? To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null not...

PHP, how to set class variable value from function

php,class,constructor
I am creating a class with variable, as you can see from the code below, I am want to access $allen = new guest(...); echo $allen->userName; instead I have to use this $allen->getUserName(); but since username won't change after the class is created, is there a way to do this?...

JavaScript code printing extra line (undefined) in output

javascript,constructor
need help with this code. What am I doing wrong? Problem: Create 10 cars, where each car has a color and number. The cars should be numbered in order from 0 to 9. The cars from 0 to 4 should be colored "green" and the cars from 5 to 9...

How can this be undefined in the constructor of an Angular config class?

angularjs,constructor,typescript,undefined,this
I've found some examples online, where people create TypeScript config classes and pass them on to Angular. When I've tried it, I got the weird exception, that this was undefined. A closer look to the other implementations revealed, they only use the constructor, so, are those examples actually inherently wrong...

Swift Does Not Recognize This Specific Objective C Class Constructor

ios,objective-c,swift,uiview,constructor
I am trying to use this class REDActionSheet.h I've imported it into my bridging header and everything. I have other Objective C class as well. XCode seems to detect the class and I could initialize it normally. However, Swift does not seem to recognize the constructor for this class Here...

the issues of calling overridable methods from constructor

java,constructor,override
if it is possible please make this sentence clear for me here, the author said: Do not call overridable methods from constructors. When creating a subclass object, this could lead to an overridden method being called before the subclass object is fully initialized. Recall that when you construct a subclass...

Do constructors always have to be public?

java,constructor
My first question is - class Explain() { public Explain() { } } Should Constructor always declared as public? And second one is - what if I create a private constructor. Is it useful? Edit - My question is about uses of private and public constructor.(And what they like?)...

C++ parameterized constructor In a templated class

c++,templates,constructor
I recently start learning templates in C++ and I am not sure if I need to include template <class T>for my implementation of a parameterized constructor. template <class T> class A { T num; //default constructor (parameterized) template <class T>//getting error A(T value) { num=value;} } I get an error...

Custom Exception: customize message before call the base constructor

c#,constructor,custom-exceptions
I defined this custom exception public class ThirdPartyServiceException : System.Exception { public ThirdPartyServiceException(string message, Exception innerException): base(message, innerException) { } } That's fine, but now I want customize the exception message before call the base constructor. Something like: public class ThirdPartyServiceException : System.Exception { public ThirdPartyServiceException(string code, string message, string...

Return new something in function returning a shared_ptr

c++,constructor,return,shared-ptr,implicit-conversion
I have a function that returns a shared_ptr to a const object. Returning a shared_ptr constructed from a pointer returned by operator new works, but returning that pointer directly causes compilation error : Error 3 error C2664: 'std::shared_ptr<_Ty>::shared_ptr(std::nullptr_t)' : cannot convert parameter 1 from 'script::float_data *' to 'std::nullptr_t' c:\xxx\value.cpp 59...

How to get a variable from another class without calling a constructor?

java,constructor,static,libgdx,box2d
So, in LibGDX I am using box2d and I have a class for contact listening. I need to get my player's body without making a class object, because it will call the constructor the second time. And a static variable is not an option. How should I do this? Here...

Trying to create Library in C++. Test project can't find implementation of declared constructor?

c++,constructor,static-libraries,header-files
I'm learning C++, but hit a plateau trying to create a library. Using Visual Studio 2013, I get this error: Error 1 error LNK2019: unresolved external symbol "public: __thiscall Polynomial::Polynomial(void)" (??0Polynomial@@[email protected]) referenced in function _main A:\Medier\Desktop\PolyLib\Test\Test.obj Test The testproject is currently cut down to this: #include "A:\Medier\Desktop\PolyLib\PolyLib\PolyLib.h" using namespace std;...

C++ classes: Is it possible to select a member's constructor in a constructor body? (Without doubly initializing the member)

c++,parameters,constructor,default-constructor,initialization-list
Consider this: class Foo { private: Bar x; public: Foo(int a) { // no initialization here since constructor is dependent on a following if-block if (a==0) x=Bar(12,'a', 34); // some (int, char, int) constructor of Bar else x=Bar(13); // (int) constructor of Bar } } What this is supposed to...

initializing python object with nothing but keyword args

python,object,constructor,instantiation
I am wondering how to initialize an object in python with only named args, and nothing else, if this is possible. If the order of self.name = name and self.age = age are swapped, the error is with initializing age. I have these given as keyword args to the object,...

C++ constructors in subclass

c++,constructor,polymorphism
hey I want to send my constructor Buttom(string) from my derived to the function setText(string) in my base , I tried to do this Buttom(string) : setText(string text){} which gives me syntax error, thanks in advance! base class: #include"RGB.h" #include"Point.h" #include"string" using namespace std; class Widget{ protected: RGB _backgroundColor,_textColor; Point...

How can I write this private method for being unique to the ticket number, and set that ticket number constructor?

methods,constructor,private
ParkingTicket Here are the relevant attributes: ticket number of type String the name of the police officer who issued the ticket the police officer's badge number the car's license number the car's make the car's model amount of the fine Note that the ticket number must be unique, created by...

Consructor using multiple arrays in java

java,arrays,string,constructor
Having trouble creating a constructor that takes multiple one dimensional arrays of Strings: class relation { String[] setA, setB, setC; relation (String[] setA, String[] setB, String[] setC) { this.setA = setA; this.setB = setB; this.setC = setC; } } public class matrix { public static void main(String[] args) { relation...

How do I initialise an array using a constructor? C++ [duplicate]

c++,arrays,constructor
This question already has an answer here: Initializing a member array in constructor initializer 5 answers I'm a beginner C++ programmer and not sure why this won't work: #include <iostream> using namespace std; class Hello { private: int mess[]; public: Hello() { mess = { 1, 3, 4, 546,...

Do I need to reimplement all the constructor of a base class even if a derived class has no member variables?

c++,inheritance,constructor
Let's assume I have a base class class Base { public: Base(); Base(int i, double j); Base(int i, double j, char ch); virtual void print(); private: int m; double l; char n; }; And I want to derive a class which overrides the print function but apart from that is...

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};...

Class constructors in C++

c++,constructor
I'm a beginner to c++ so there are a lot of things quite not clear in my mind. I have this code I need to write and in a class I make a constructor. However, I don't need any parameters because I read from a file-stream inside the constructor. So...

StackOverflowError exception in constructor

java,constructor
I received this exception. Exception in thread "main" java.lang.StackOverflowError at java.util.AbstractCollection.<init>(AbstractCollection.java:66) at java.util.AbstractList.<init>(AbstractList.java:76) at java.util.ArrayList.<init>(ArrayList.java:151) Does that mean a class can't contain objects of itself as a variable? But in a linked list implementation, a node can contain a node pointing to itself? public class Test { String name; List<Test>...

Passing an array through a constructor

java,arrays,constructor
This is what I have so far: import java.util.*; public class SArray { private int[] array; public SArray(int a[]) { this.array = a; } public String toString() { String arrayString = ""; int i = 0; while (i < array.length) { arrayString = arrayString + array[i]; i++; } return arrayString;...

How to pass additional arguments to a Constructor when extending a LinearLayout in Android?

android,class,constructor,android-linearlayout,extend
I have the following question, if I have a class extending a LinearLayout like: public class ExtendedSeekbarLayout extends LinearLayout { ..} and I would like to pass additional Arguments to my Layout, how do I do this? I know that I could have the following constructors like: public ExtendedSeekbarLayout (Context...

Why does Java prefer to call double constructor?

java,constructor
public class test { test(double[] a) { System.out.println("in double"); } test(Object a) { System.out.println("in object"); } public static void main(String args[]) { new test(null); } } In the above code, I pass null as the constructor argument. As null can be anything, the above code compiles fine. When I run...

VS2013 Unresolved External with constructor and destructor [duplicate]

c++,visual-studio-2013,constructor,linker-error
This question already has an answer here: What is an undefined reference/unresolved external symbol error and how do I fix it? 18 answers I am trying to make a linked list program that will add two polynomials together, pretty simple. However, whenever I try and build this program, I...

Why Constructor is not Calling with Function call Operators [duplicate]

c++,constructor
This question already has an answer here: Default constructor with empty brackets 7 answers Sorry I was unable to find any keyword to search for this problem. My code is below #include <iostream> using namespace std; class Name { public: Name() { cout << "Asif"; } }; int main()...

Constructor argument not inheriting down to children?

php,oop,inheritance,constructor
I am new to php and in particular to oop. I have this piece of test code that I thought would return: What is the result?8 What is the result?8 But, instead I am getting: What is the result?5 What is the result?8 The arguments passed into the instance of...

Java - How to only create an object with valid attributes?

java,validation,object,constructor
I'm doing a basic Java course and I came to a problem: How do I create an object only if I have passed valid parameters to the Constructor? Should I make an alternate class and call the constructor from there after the validation is realized? Or should/could I use a...

c++ extend constructor of same class (no inheritance)

c++,constructor
I might have found my answer somewhere here, but nevertheless, I'd like to be sure. I am making something represented in a graph (hence the nodes), and I wondered if this code of the constructors is working the way I think. G++ doesn't complain. I have the following class: #ifndef...

C++ compiler thinks my constructor definition is a method [closed]

c++,constructor
I'm getting the following errors: C:\Users\James\cavewhere\dewalls\src\unit.cpp:6: error: C2511: 'dewalls::Unit::Unit(QString,dewalls::UnitType *)' : overloaded member function not found in 'dewalls::Unit' C:\Users\James\cavewhere\dewalls\src\unit.cpp:9: error: C2550: 'dewalls::Unit::{ctor}' : constructor initializer lists are only allowed on constructor definitions unit.h: #ifndef UNIT_H #define UNIT_H class UnitType; #include <QString> namespace dewalls { class Unit { public: Unit(QString name,...

Initializing a struct from a constructor

c++,struct,constructor,g++
I'm getting back into writing some C++ and I'm honestly rusty. I get the feeling I'd find a quick answer to my question if I just knew how to phrase it properly, but still I'd appreciate your help. sanitycheck.cpp: #include <string> using namespace std; typedef struct STR_1 { int val_a,...

Is it possible to access the current 'to create' obj in constructor?

c++,object,constructor
I am currently writing a tree class and want to implement a constructor for creating a tree with a certain dimension and depth: public: tree(); // empty constructor tree(int dimension, int depth); // constructing an empty tree // ... void newNode(node<T>* const&, T const&); // ... private: unsigned int mNumNodes;...

Throwing an exception in constructor (java)

java,exception,constructor
Utwor(String x, String y, Integer z) { tytul1 = x; wykonawca2 = y; rok3 = z; if (z < 1900 || z > 2015) { System.out.println("Rok utworu musi się zawierać pomiędzy 1900, a 2015."); throw new IllegalArgumentException("Invalid cents value: " + z); } } z is supposed to be between...

JS Power Constructor and instanceof without new

javascript,constructor,prototype,new-operator
To quote this guy we can use a power constructor which has the form function constructor() { var that = {}; that.data = true; that.method = function () {}; return that; } To create objects that will behave correctly with or without the new keyword. My question is how do...

How to use Guice Module to instantiate one of multiple fields in a class?

java,constructor,dependency-injection,guice
I have a class, and create an instance using a regular constructor: class Foo { String fooName; Bar barObject; ExternalService externalService; Foo(String fooName, Bar barObject, Service someService){ this.fooName = fooName; this.barObject = barObject; this.externalService = externalService; //call to super } } class MyApplication { //instantiate ExternalService ... Foo foo =...