Questions tagged [constructor]
A special type of subroutine called at the creation of an object.
constructor
21,134
questions
3683
votes
11
answers
1.2m
views
What does the explicit keyword mean?
What does the explicit keyword mean in C++?
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 ...
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 = "...
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 ...
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?
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;
...
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);
...
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();
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 ...
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 ...
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 ...
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?
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 ...
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?
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'...
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. ...
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 ...
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 (...
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()
{
...
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 (...
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 << ...
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 ...
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 ...
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("...
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 ...
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?
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?
...
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 ...
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 ...
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() {}
...
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 ...
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 ...
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 ...
310
votes
23
answers
287k
views
Why do we not have a virtual constructor in C++?
Why does C++ not have a virtual constructor?
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.
...
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. ...
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 ...
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 ...
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?
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?
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 ...
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, ...
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
{
...
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 ...
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 ...
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();
}
}
251
votes
16
answers
251k
views
Can a constructor in Java be private?
Can a constructor be private? How is a private constructor useful?
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 ...
235
votes
7
answers
155k
views
Can constructors throw exceptions in Java?
Are constructors allowed to throw exceptions?