C# FAQ: Are constructors the same in Cplusplus and CSharp

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

Are constructors the same in C++ and C#?

Although there are strong similarities between C# constructors and C++ constructors, there are, also, some significant differences.

Firstly, C# supports constructor chaining—one constructor can call another as in the following example:

class Employee
{
   public Employee (string name, int salary) { ... }
 
   public Employee (string name) : this (salary, 0) {}
 
   public Employee() : this ("", 0) {}
}

Secondly, virtual method calls within a constructor are directed to the most derived implementation.

Thirdly, error handling is a bit different. When an exception occurs during C# object construction, the destructor—finalizer—will be called. This behavior differs from C++ behavior in which the destructor is not called if construction is interrupted.

Lastly, C# has static constructors. A static constructor for a class executes before the first instance of the class is created.

Interestingly, some C# developers—like some C++ developers—prefer the factory pattern to constructors.


See also



Personal tools