Questions tagged [constructor]

2.5k

votes
11

answer
711.8k

Views
1.9k

votes
18

answer
706.5k

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 it)?
ashokgelal
1.9k

votes
8

answer
235.8k

Views

What is The Rule of Three?

What does copying an object mean? What are the copy constructor and the copy assignment operator? When do I need to declare them myself? How can I prevent my objects from being copied?
fredoverflow
1.7k

votes
5

answer
293.9k

Views

What is the copy-and-swap idiom?

What is this idiom and when should it be used? Which problems does it solve? Does the idiom change when C++11 is used? Although it's been mentioned in many places, we didn't have any singular 'what is it' question and answer, so here it is. Here is a partial list of places where it was previously me...
GManNickG
1.2k

votes
10

answer
867.3k

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 Exception class I want to do something like this: class MyExceptionClass : Exception { public MyExceptionCl...
lomaxx
1.2k

votes
17

answer
152.7k

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
936

votes
5

answer
99.6k

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
807

votes
8

answer
372.1k

Views

Call one constructor from another

I have two constructors which feed values to readonly fields. class Sample { public Sample(string theIntAsString) { int i = int.Parse(theIntAsString); _intField = i; } public Sample(int theInt) { _intField = theInt; } public int IntProperty { get { return _intField; } } private readonly int _intFiel...
Avi
787

votes
15

answer
384.4k

Views

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

As a C# developer I'm used to run through constructors: class Test { public Test() { DoSomething(); } public Test(int count) : this() { DoSomethingWithCount(count); } public Test(int count, string name) : this(count) { DoSomethingWithName(name); } } Is there a way to do this in C++? I tried calling...
Stormenet
641

votes
20

answer
288k

Views

Difference between Constructor and ngOnInit

Angular provides life cycle hook ngOnInit by default. Why should ngOnInit be used, if we already have a constructor?
Haseena P A
586

votes
9

answer
675.7k

Views

What are the rules for calling the superclass constructor?

What are the C++ rules for calling the superclass constructor from a subclass one? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
levik
575

votes
11

answer
211.3k

Views

What is a clean, pythonic way to have multiple constructors in Python?

I can't find a definitive answer for this. AFAIK, you can't have multiple __init__ functions in a Python class. So how do I solve this problem? Suppose I have an class called Cheese with the number_of_holes property. How can I have two ways of creating cheese-objects... one that takes a number of h...
winsmith
568

votes
22

answer
616.2k

Views

How to initialize HashSet values by construction?

I need to create a Set with initial values. Set h = new HashSet(); 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 final static field.
Serg
525

votes
19

answer
186k

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 extends MyClass { public MySubClass(int a, int b) { int c = a + b; super(c); // COMPILE ERROR } } The Sun co...
Joe Daley
515

votes
21

answer
480.6k

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
485

votes
4

answer
167.9k

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
470

votes
17

answer
246.7k

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's a game) IDrawable +Update +Draw To be able to Update (check for edge of screen etc) and draw itself...
Boris Callens
435

votes
30

answer
67k

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 (but the code below does not work): function Something(){ // init stuff } function createSomething(){ re...
Premasagar
343

votes
14

answer
159.1k

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 UserA = function(nameParam) { this.id = MY_GLOBAL.nextId(); this.name = nameParam; } UserA.prototype.sa...
Graham King
340

votes
7

answer
105.3k

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('title', getTitle())); } protected abstract String getTitle(); } NetBeans warns me with the message 'Overridable met...
deamon
312

votes
8

answer
59.5k

Views

Rule-of-Three becomes Rule-of-Five with C++11?

So, after watching this wonderful lecture on rvalue references, I thought that every class would benefit of such a 'move constructor', template MyClass(T&& other) edit and of course a 'move assignment operator', template MyClass& operator=(T&& other) as Philipp points out in his answer, if it has dy...
Xeo
305

votes
19

answer
152.1k

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 __construct($id){ $this->id = $id; // other members are still uninitialized } public function __construct($row_from_da...
Jannie Theunissen
298

votes
12

answer
92.8k

Views

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

Recently I've seen an example like the following: #include class Foo { public: int bar; Foo(int num): bar(num) {}; }; int main(void) { std::cout
nils
294

votes
16

answer
438.5k

Views

Struct 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.
264

votes
10

answer
123.4k

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 an actual list. What's your technique for doing this? Do you just check the type by looking at __clas...
Baltimark
262

votes
3

answer
147.9k

Views

Chain-calling parent constructors in python [duplicate]

This question already has an answer here: How to invoke the super constructor? 5 answers 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 constructor in a constructor? If this still sounds too vague, here's some code....
shylent
259

votes
6

answer
186.2k

Views

How to invoke the super constructor?

class A: def __init__(self): print 'world' class B(A): def __init__(self): print 'hello' B() hello In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn't work.
Mike
252

votes
9

answer
141.8k

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
237

votes
10

answer
164.7k

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? Lets say I'm wrapping a POSIX mutex in a class, it would look something like this: class Mutex { publ...
lkristjansen
228

votes
4

answer
50.1k

Views

What is a higher kinded type in Scala?

You can find the following on the web: Higher kinded type == type constructor? class AClass[T]{...} // For example, class List[T] Some say this is a higher kinded type, because it abstracts over types which would be compliant with the definition. Higher kinded types are types which take other types...
Lutz
217

votes
8

answer
116.4k

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?
213

votes
20

answer
198.6k

Views
213

votes
8

answer
135.4k

Views

Can constructors throw exceptions in Java?

Are constructors allowed to throw exceptions?
Mahmoud Hossam
206

votes
13

answer
85.3k

Views

Calling virtual functions inside constructors

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() {} virtual void fn() { _n = 2; } }; If I write the following code: int main() { B b; int n = b.getn(); } One might expe...
David Coufal
202

votes
13

answer
87.7k

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
198

votes
10

answer
98.4k

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 overload the constructor of this anonymous class. Like shown below Object a = new Class1(){ void someNewMethod(){ } public XXXXXXXX...
Saravanan M
197

votes
15

answer
187.3k

Views

Can a constructor in Java be private?

Can a constructor be private? How is a private constructor useful?
Rajesh
192

votes
8

answer
116.2k

Views

C# constructor chaining? (How to do it?)

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 class, so I'm just learning. I don't understand how constructor chaining works or how to implement it, or ev...
Alex
192

votes
11

answer
94.2k

Views

Can constructors be async?

I have a Silverlight project where I'm trying to populate some data in a constructor: public class ViewModel { public ObservableCollection Data { get; set; } async public ViewModel() { Data = await GetDataTask(); } public Task GetDataTask() { Task task; //Create a task which represents getting the d...
Marty Neal
185

votes
25

answer
54k

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 refuse to create an object -- if the object isn't complete. I.e., the constructor should have a contract...
Mark R Lindsey