Reputation: 380
public class Animal
{
public Animal()
{
"animal ctor".Dump();
}
}
public class Cat :Animal
{
public Cat():this("gray")
{
"cat ctor".Dump();
}
public Cat(string c):base()
{
"cat ctor2".Dump();
}
}
void Main()
{
Cat a = new Cat();
}
The code's output is :
animal ctor
cat ctor2
cat ctor
I understand the first line.
The Animal Ctor is called first, but then the Cat ctor is calling the string overload public Cat(string c):base()
- but this ALSO calls base's constructor.
So why I don't see animal ctor
again (:base()
)?
Upvotes: 2
Views: 1024
Reputation: 101681
the constructor is only called once:
Cat()
constructor calls Cat(string c)
Cat(string c)
is calling base constructorCat(string c)
is executed (which is the caller of base)Cat()
constructor is executedBasically if you call the base constructor (or another constructor in your class), that is executed before your constructor.See the documentation for more details
Upvotes: 5
Reputation: 38130
Cat()
explicitly calls Cat(string)
which explicitly calls Animal()
.
These calls happen before each method starts, so you see them dumped in reverse order.
Cat()
does not call Animal()
directly, meaning the base class' constructor would only be called once (which, is probably what you want)
If you don't explicitly specify which constructor to call, then the default constructor for the base class is called; So the following:
public Cat(string c) :base()
{
"cat ctor2".Dump();
}
Is equivalent to:
public Cat(string c)
{
"cat ctor2".Dump();
}
Upvotes: 1
Reputation: 1565
There are a few rules of inheritance and object construction.
Here, the constructor is called in sequence Cat() : this(string) which is Cat(string) : base() which is Animal()
Animal is base of Cat so Animal is constructed first. once Animal() constructor call is finished, then Cat(string) will complete and subsequently Cat() invocation will be completed.
Even if you do not mention base(), base will still be invoked. A parameterless constructor is always invoked by default (if available) and this process is bubbled up to the topmost parent in hierarchy.
A parameterless constructor is always present for every class. But, if you declare one with a parameter, then you explicitly need to declare a parameterless constructor.
Upvotes: 0