constructor interview questions
Top constructor frequently asked interview questions
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)?
Source: (StackOverflow)
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?
Source: (StackOverflow)
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 command?
Source: (StackOverflow)
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_database){
$this->id = $row_from_database->id;
$this->name = $row_from_database->name;
// etc.
}
}
What is the best way to do this in PHP?
Source: (StackOverflow)
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 MyExceptionClass(string message, string extraInfo)
{
//This is where it's all falling apart
base(message);
}
}
Basically what I want is to be able to pass the string message to the base Exception class.
Source: (StackOverflow)
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 _intField;
}
One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.
Now here's the catch:
- I don't want to duplicate the
setting code. In this case, just one
field is set but of course there may
well be more than one.
- To make the fields readonly, I need
to set them from the constructor, so
I can't "extract" the shared code to
a utility function.
- I don't know how to call one
constructor from another.
Any ideas?
Source: (StackOverflow)
If 'Test' is an ordinary class, is there any difference between:
Test* test = new Test;
and
Test* test = new Test();
Source: (StackOverflow)
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 it will always need a GraphicsDeviceManager
. So I want to make sure the object has a reference to it. This would belong in the constructor.
Now that I wrote this down I think what I'm implementing here is IObservable
and the GraphicsDeviceManager
should take the IDrawable
...
It seems either I don't get the XNA framework, or the framework is not thought out very well.
Edit
There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.
Source: (StackOverflow)
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(){
return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something
The Answer
From the responses here, it became clear that there's no in-built way to call .apply()
with the new
operator. However, people suggested a number of really interesting solutions to the problem.
My preferred solution was this one from Matthew Crumley (I've modified it to pass the arguments
property):
var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}
})();
Source: (StackOverflow)
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 method call in constructor", but what should be wrong with it? The only alternative I can imagine is to pass the results of otherwise abstract methods to the super constructor in subclasses. But that could be hard to read with many parameters.
Source: (StackOverflow)
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 compiler says "call to super must be first statement in constructor". The Eclipse compiler says "Constructor call must be the first statement in a constructor".
However, you can get around this by re-arranging the code a little bit:
public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
super(a + b); // OK
}
}
Here is another example:
public class MyClass {
public MyClass(List list) {}
}
public class MySubClassA extends MyClass {
public MySubClassA(Object item) {
// Create a list that contains the item, and pass the list to super
List list = new ArrayList();
list.add(item);
super(list); // COMPILE ERROR
}
}
public class MySubClassB extends MyClass {
public MySubClassB(Object item) {
// Create a list that contains the item, and pass the list to super
super(Arrays.asList(new Object[] { item })); // OK
}
}
So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.
There are similar rules for calling this()
. The compiler says "call to this must be first statement in constructor".
Why does the compiler have these restrictions? Can you give a code example where, if the compiler did not have this restriction, something bad would happen?
Source: (StackOverflow)
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.sayHello = function() {
console.log('Hello '+ this.name);
}
var bob = new UserA('bob');
bob.sayHello();
(Assume MY_GLOBAL.nextId exists).
The best I can come up with is:
var userB = {
init: function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var bob = Object.create(userB);
bob.init('Bob');
bob.sayHello();
There doesn't seem to be any advantage, so I think I'm not getting it. I'm probably being too neo-classical. How should I use Object.create
to create user 'bob'?
Source: (StackOverflow)
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 course a "move assignment operator", template<class T> MyClass& operator=(T&& other)
as Philipp points out in his answer, if it has dynamically allocated members, or generally stores pointers. Just like you should have a copy-ctor, assignment operator and destructor if the points mentioned before apply.
Thoughts?
Source: (StackOverflow)