Skip to main content

Questions tagged [constructor]

A special type of subroutine called at the creation of an object.

Filter by
Sorted by
Tagged with
3683 votes
11 answers
1.2m views

What does the explicit keyword mean?

What does the explicit keyword mean in C++?
Skizz's user avatar
  • 70.5k
2686 votes
22 answers
1.2m views

How do I call one constructor from another in Java?

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do ...
ashokgelal's user avatar
2329 votes
23 answers
1.3m views

What is the best way to give a C# auto-property an initial value?

How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "...
bentford's user avatar
  • 33.3k
1857 votes
10 answers
1.4m views

Calling the base constructor in C#

If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that? For example, if I inherit from the ...
lomaxx's user avatar
  • 115k
1493 votes
18 answers
226k views

Virtual member call in a constructor

I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. Why would this be something not to do?
JasonS's user avatar
  • 23.7k
1335 votes
11 answers
679k views

Call one constructor from another

I have two constructors which feed values to readonly fields. public class Sample { public Sample(string theIntAsString) { int i = int.Parse(theIntAsString); _intField = i; ...
Avi's user avatar
  • 16k
1161 votes
15 answers
648k views

Can I call a constructor from another constructor (do constructor chaining) in C++?

As a C# developer I'm used to running through constructors: class Test { public Test() { DoSomething(); } public Test(int count) : this() { DoSomethingWithCount(count); ...
Stormenet's user avatar
  • 26.5k
1116 votes
8 answers
141k views

Do the parentheses after the type name make a difference with new?

If 'Test' is an ordinary class, is there any difference between: Test* test = new Test; and Test* test = new Test();
David Read's user avatar
  • 11.1k
964 votes
16 answers
480k views

What is a clean "pythonic" way to implement multiple constructors?

I can't find a definitive answer for this. As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve this problem? Suppose I have a class called Cheese with the ...
winsmith's user avatar
  • 21.4k
942 votes
25 answers
1.1m views

How to initialize HashSet values by construction?

I need to create a Set with initial values. Set<String> h = new HashSet<String>(); h.add("a"); h.add("b"); Is there a way to do this in one line of code? For instance, it's useful for a ...
Serg's user avatar
  • 13.9k
868 votes
10 answers
1.1m views

What are the rules for calling the base class constructor?

What are the C++ rules for calling the base class constructor from a derived class? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an ...
levik's user avatar
  • 117k
742 votes
22 answers
798k views

Can an abstract class have a constructor?

Can an abstract class have a constructor? If so, how can it be used and for what purposes?
Szere Dyeri's user avatar
  • 15.2k
735 votes
23 answers
347k views

Why do this() and super() have to be the first statement in a constructor?

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why? For example: public class MyClass { public MyClass(int x) {} } public class MySubClass ...
Joe Daley's user avatar
  • 46.1k
715 votes
8 answers
232k views

What is the difference between using constructor vs getInitialState in React / React Native?

I've seen both used interchangeably. What are the main use cases for both? Are there advantages / disadvantages? Is one a better practice?
Nader Dabit's user avatar
  • 53.3k
644 votes
18 answers
441k views

Interface defining a constructor signature?

It's weird that this is the first time I've bumped into this problem, but: How do you define a constructor in a C# interface? Edit Some people wanted an example (it's a free time project, so yes, it'...
Boris Callens's user avatar
607 votes
18 answers
436k views

Constructor overload in TypeScript

Has anybody done constructor overloading in TypeScript. On page 64 of the language specification (v 0.8), there are statements describing constructor overloads, but there wasn't any sample code given. ...
Ted's user avatar
  • 6,171
519 votes
7 answers
408k views

How to invoke the super constructor in Python?

class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") B() # output: hello In all other languages I've worked with the super constructor ...
Mike's user avatar
  • 60.1k
504 votes
17 answers
881k views

Can a struct have a constructor in C++?

Can a struct have a constructor in C++? I have been trying to solve this problem but I am not getting the syntax.
483 votes
36 answers
85k views

Use of .apply() with 'new' operator. Is this possible?

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible? What I want to do is something like this (...
Prem's user avatar
  • 16.1k
475 votes
17 answers
351k views

Can constructors be async?

I have a project where I'm trying to populate some data in a constructor: public class ViewModel { public ObservableCollection<TData> Data { get; set; } async public ViewModel() { ...
Marty Neal's user avatar
  • 9,227
452 votes
10 answers
1.7m views

Why do I get "TypeError: Missing 1 required positional argument: 'self'"?

I have some code like: class Pump: def __init__(self): print("init") def getPumps(self): pass p = Pump.getPumps() print(p) But I get an error like: Traceback (...
DominicM's user avatar
  • 6,760
445 votes
14 answers
147k views

What is this weird colon-member (" : ") syntax in the constructor?

Recently I've seen an example like the following: #include <iostream> class Foo { public: int bar; Foo(int num): bar(num) {}; }; int main(void) { std::cout << Foo(42).bar << ...
nils's user avatar
  • 4,769
441 votes
10 answers
269k views

How to overload __init__ method based on argument type?

Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with ...
Baltimark's user avatar
  • 9,222
406 votes
25 answers
246k views

Best way to do multiple constructors in PHP

You can't put two __construct functions with unique argument signatures in a PHP class. I'd like to do this: class Student { protected $id; protected $name; // etc. public function ...
Jannie Theunissen's user avatar
405 votes
8 answers
149k views

What's wrong with overridable method calls in constructors?

I have a Wicket page class that sets the page title depending on the result of an abstract method. public abstract class BasicPage extends WebPage { public BasicPage() { add(new Label("...
deamon's user avatar
  • 91.3k
391 votes
15 answers
203k views

Using "Object.create" instead of "new"

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new in the code below with Object.create? var ...
Graham King's user avatar
  • 5,700
388 votes
8 answers
238k views

What is the use of static constructors?

Please explain to me the use of static constructor. Why and when would we create a static constructor and is it possible to overload one?
Dr. Rajesh Rolen's user avatar
352 votes
11 answers
284k views

Throwing exceptions from constructors

I'm having a debate with a co-worker about throwing exceptions from constructors, and thought I would like some feedback. Is it OK to throw exceptions from constructors, from a design point of view? ...
lkristjansen's user avatar
  • 3,624
350 votes
9 answers
80k views

Rule-of-Three becomes Rule-of-Five with C++11? [closed]

So, after watching this wonderful lecture on rvalue references, I thought that every class would benefit of such a "move constructor", template<class T> MyClass(T&& other) edit and of ...
Xeo's user avatar
  • 131k
338 votes
10 answers
218k views

Spring @Autowired on Properties vs Constructor

So since I've been using Spring, if I were to write a service that had dependencies I would do the following: @Component public class SomeService { @Autowired private SomeOtherService ...
GSUgambit's user avatar
  • 4,729
336 votes
16 answers
161k views

Why is a call to a virtual member function in the constructor a non-virtual call?

Suppose I have two C++ classes: class A { public: A() { fn(); } virtual void fn() { _n = 1; } int getn() { return _n; } protected: int _n; }; class B : public A { public: B() : A() {} ...
David Coufal's user avatar
  • 6,211
330 votes
8 answers
392k views

Inheriting constructors

Why does this code: class A { public: explicit A(int x) {} }; class B: public A { }; int main(void) { B *b = new B(5); delete b; } Result in these errors: main.cpp: In ...
Sydius's user avatar
  • 14k
330 votes
12 answers
208k views

difference between variables inside and outside of __init__() (class and instance attributes)

Is there any difference at all between these classes besides the name? class WithClass (): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class ...
Teifion's user avatar
  • 110k
312 votes
11 answers
234k views

Constructors in Go

I have a struct and I would like it to be initialised with some sensible default values. Typically, the thing to do here is to use a constructor but since go isn't really OOP in the traditional sense ...
Marty Wallace's user avatar
310 votes
23 answers
287k views

Why do we not have a virtual constructor in C++?

Why does C++ not have a virtual constructor?
Arjun's user avatar
  • 3,207
307 votes
5 answers
354k views

Is it not possible to define multiple constructors in Python? [duplicate]

Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it? For example, let's say you wanted to define a class City. ...
Chris's user avatar
  • 21.9k
303 votes
4 answers
89k views

What is the order of evaluation in a member initializer list?

I have a constructor that takes some arguments. I had assumed that they were initialized in the order listed, but in one case, it appears they were being initialized in reverse, resulting in an abort. ...
hookenz's user avatar
  • 38.1k
298 votes
3 answers
180k views

Chain-calling parent initialisers in python [duplicate]

Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class initialiser in an initialiser? If this still sounds too vague, here's ...
shylent's user avatar
  • 10.1k
292 votes
15 answers
270k views

Call asynchronous method in constructor?

Summary: I would like to call an asynchronous method in a constructor. Is this possible? Details: I have a method called getwritings() that parses JSON data. Everything works fine if I just call ...
Kaan Baris Bayrak's user avatar
273 votes
9 answers
176k views

Can I use Class.newInstance() with constructor arguments?

I would like to use Class.newInstance() but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
user avatar
271 votes
15 answers
269k views

Constructor of an abstract class in C#

Why is it possible to write constructor for an abstract class in C#? As far as I know we can't instantiate an abstract class.. so what is it for? You can't instantiate the class, right?
Mulder's user avatar
  • 2,897
271 votes
9 answers
196k views

How to do constructor chaining in C#

I know that this is supposedly a super simple question, but I've been struggling with the concept for some time now. My question is, how do you chain constructors in C#? I'm in my first OOP ...
Alex's user avatar
  • 65.4k
271 votes
9 answers
170k views

Why should I prefer to use member initializer lists?

I'm partial to using member initializer lists for my constructors, but I've long since forgotten the reasons behind this. Do you use member initializer lists in your constructors? If so, why? If not, ...
oz10's user avatar
  • 157k
269 votes
15 answers
319k views

How do I get a PHP class constructor to call its parent's parent's constructor?

I need to have a class constructor in PHP call its parent's parent's (grandparent?) constructor without calling the parent constructor. // main class that everything inherits class Grandpa { ...
Paulo's user avatar
  • 4,293
269 votes
11 answers
331k views

ReactJS: Warning: setState(...): Cannot update during an existing state transition

I am trying to refactor the following code from my render view: <Button href="#" active={!this.state.singleJourney} onClick={this.handleButtonChange.bind(this,false)} >Retour</Button> to ...
user3611459's user avatar
  • 3,361
259 votes
23 answers
103k views

When is it right for a constructor to throw an exception?

When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init'er to return nil?) It seems to me that a constructor should fail -- and thus ...
Mark R Lindsey's user avatar
254 votes
15 answers
108k views

Should I instantiate instance variables on declaration or in the constructor?

Is there any advantage for either approach? Example 1: class A { B b = new B(); } Example 2: class A { B b; A() { b = new B(); } }
DonX's user avatar
  • 16.3k
251 votes
16 answers
251k views

Can a constructor in Java be private?

Can a constructor be private? How is a private constructor useful?
Rajesh's user avatar
  • 8,587
238 votes
10 answers
140k views

Accessing constructor of an anonymous class

Lets say I have a concrete class Class1 and I am creating an anonymous class out of it. Object a = new Class1(){ void someNewMethod(){ } }; Now is there any way I could ...
Saravanan M's user avatar
  • 4,747
235 votes
7 answers
155k views

Can constructors throw exceptions in Java?

Are constructors allowed to throw exceptions?
Mahmoud Hanafy's user avatar

1
2 3 4 5
423