Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are abstract class constructors not implicitly called when a derived class is instantiated?

Take this example:

abstract class Base {     function __construct() {         echo 'Base __construct<br/>';     } }  class Child extends Base {     function __construct() {         echo 'Child __construct<br/>';     } }  $c = new Child();    

Coming from a C# background, I expect the output to be

Base __construct
Child __construct

However, the actual output is just

Child __construct

like image 906
scottm Avatar asked Feb 23 '10 19:02

scottm


People also ask

Why abstract class can include constructor even though you Cannot instantiate an abstract class?

1) Abstract classes have constructors and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super() .

Does an abstract class have a constructor?

Like any other classes in Java, abstract classes can have constructors even when they are only called from their concrete subclasses.

What is abstract class constructor called?

Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.

Can we call constructor of abstract class in C#?

Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated.


1 Answers

No, the constructor of the parent class is not called if the child class defines a constructor.

From the constructor of your child class, you have to call the constructor of the parent's class :

parent::__construct(); 

Passing it parameters, if needed.

Generally, you'll do so at the beginning of the constructor of the child class, before any specific code ; which means, in your case, you'd have :

class Child extends Base {     function __construct() {         parent::__construct();         echo 'Child __construct<br/>';     } } 


And, for reference, you can take a look at this page of the PHP manual : Constructors and Destructors -- it states (quoting) :

Note: Parent constructors are not called implicitly if the child class defines a constructor.
In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

like image 68
Pascal MARTIN Avatar answered Sep 28 '22 09:09

Pascal MARTIN