0
It is understood that a class can have many constructors.... (Question continued below):
If there are multiple objects instantiated in the class , can they all have different constructors like below: using System; namespace Sololearn { class Program { class cat { public cat() { Console.WriteLine("Meow"); } public cat1() { Console.WriteLine("Meow1"); } } static void Main(string[] args) { cat c = new cat(); cat c1 = new cat1(); } } }
4 Respostas
+ 4
You can have 'n' number of constructors in a class but there could be only 1 default constructor and the rest must be overloaded.
To get some simple operations or assignments done, you can use constructor chaining. It basically calls one constructor from another.
Here is a simple example.
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
Cat c1 = new Cat("Meow is called first");
}
}
}
class Cat{
public Cat(){
Console.WriteLine("Meow");
}
public Cat(String s):this(){
Console.WriteLine(s);
}
}
+ 5
There is only one class cat so creating a new object of class cat1 which doesn't exist will give an error
+ 1
Yes, but the constructors have to have different forms and the same name i.e. as follows:
class Program
{
static void Main(string[] args)
{
cat c = new cat();
cat c1 = new cat(1);
}
class cat
{
public cat()
{
Console.WriteLine("Meow");
}
public cat(int c)
{
Console.WriteLine("Meow1");
}
}
}