Which constructor will called first in the below example? When i put break point and execute it first pointed to child constructor but executed the parent class constructor, why this?
could any one please clarify me?
class Program
{
static void Main(string[] args)
{
Child child = new Child();
child.print();
Console.ReadLine();
}
}
public class Parent
{
public Parent()
{
Console.WriteLine("Parent Constructor.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor.");
}
public new void print()
{
Console.WriteLine("I'm a Child Class.");
}
}
Constructors, when generated from C#, are invoked base-class first, so:
object()
then Parent()
then Child()
Essentially the chained base:.ctor({args}) is prepended to the local .ctor
For this reason you should avoid calling virtual methods during construction, as if Child overrides it, it could fail as Child hasn't initialized the fields defined there yet (they will be zeros).
In C++/CLI you get to choose what order to do things.
Parent is constructed first because it's at the heart of Child.
Child can't be constructed if it's core (Parent) isn't.
Note that the initialization of the class is not limited to executing its constructor. It also initializes its fields.
In the example below, you really want Child's constructor to show that x=3. If not, it would mean that your derived class can't be based on its ancestor behaviour.
public class Parent
{
public int x;
public Parent()
{
x = 3;
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Constructor. x="+x.ToString());
}
}
Related
I am wondering what would theoretically be the output of this code?
Basically I am overwriting a method in the child class but I am calling that
method in the parent class. I am hoping the output of this would be "Child"
public class Animal {
protected virtual void Activate() {
Debug.Log("Parent");
}
void CallStuff() {
Activate();
}
}
public class Frog : Animal {
override void Activate() {
Debug.Log("Child");
}
}
If I were to have a frog instance frog and call ...
frog.CallStuff();
What would the output be?
Perhaps some examples will explain best:
Let's start with a base class:
public class Parent {
public virtual string WhatAmI() {
return "Parent";
}
public string Output() {
return this.WhatAmI();
}
}
Calling the Output method will, of course, give you "Parent"
new Parent().Output(); // "Parent"
Now let's override that virtual method
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
}
Now when you call Output(), it returns "Child"
new OverridingChild().Output(); // "Child"
And if you cast it to a Parent, you get the same result:
((Parent) new OverridingChild()).Output(); // "Child"
If you want the base class's value, you have to call base from within the inheriting class:
public class OverridingChild : Parent {
public override string WhatAmI() {
return "Child";
public string OutputBase() {
return base.WhatAmI();
}
}
new OverridingChild().OutputBase(); // "Parent"
Now for the confusing bit - here's how you can get either value, depending on what class the compiler thinks the object is:
public class NewMethodChild : Parent {
// note that "new" keyword
public new string WhatAmI() {
return "Child";
}
Calling the method directly when the compiler thinks it's the inheriting class gets you the expected result:
new NewMethodChild().WhatAmI(); // "Child"
But if you cast it to the base class, you get the Parent result:
((Parent) new NewMethodChild()).WhatAmI(); // "Parent"
And if you call the Output method, because it is defined at the Parent class it doesn't see the new WhatAmI method of the inheriting class, so it also outputs the base value:
new NewMethodChild().Output(); // "Parent"
Hope that clears things up.
the output would be "Child" It inherited the Call Stuff function but overrode the Activate function so you'd get Child
I have inherited property in my children class. But when I am trying to call parent method, it always using it's own (parent) property. How I can explain c# to use inherited property?
class ParentClass
{
protected int autoinc;
public ParentClass()
{
autoinc = 1000;
}
public Show()
{
Debug.Log("AutoInc = " + autoinc);
}
}
class ChildClass : ParentClass
{
protected int autoinc;
public ChildClass()
{
autoinc = 2000;
}
}
/* Calling code */
ChildClass cc = new ChildClass();
cc.Show();
// I need above code to show 2000, but it shown 1000.
Sorry, this is definitely stupid question. But I need your help anyway.
autoinc field in child class hides declaration of field with same name in parent class. Just remove that field from child class:
class ChildClass : ParentClass
{
public ChildClass()
{
autoinc = 2000;
}
}
Remember, when you use inheritance, then Child object is Parent object. You don't need to define parent fields or other members in child object, because they all are already here. Unless you want to hide or override some member of parent class.
I have a parent class with 2 constructor and the derived class trying to call the constructor of parent in 2 different methods
public class Parent
{
public Parent()
{
//some stuffs
}
public Parent(string st)
{
//some stuffs
}
}
Now I have a derived class with two methods.
I Have to use Parent-constructor in one method and the Parent(string st) in other method.
But here It is always calling the Parent-constructor. Below is the derived class
public class Derived : Parent
{
public void GetData()
{
//Here I initialize the constructor like this
Parent p = new Parent();
}
public void GetData1()
{
string s = "1";
Parent p = new Parent(s);
}
}
Please let me how to make this happen.
Thanks in advance.
Just have two constructors in your Derived class that use the appropriate constructor in the base.
public class Derived : Parent
{
public Derived() : base()
{
}
public Derived(string s) : base(s)
{
}
}
The :base() nomenclature will invoke the parent constructor.
Use the parent constructor call "base"
public class Parent {
public Parent() {}
public Parent(string s) {}
}
public class Child : Parents {
public Child():base() // Call Parent empty constructor
public Child(string s): base(s) // Call Parent Constructor with parameter
}
Your error comes because you're instanciate a new Object Parents in your Child.
With Base(), you call the parent constructor without instanciate him.
Calling new Derived() will call the Parent() ctor because it inherits from Parent and has an implicit Derived() : base().
After you have constructed Derived() calling the method (not constructor) GetData1() will call the Parent(string st) constructor
These are completely separate routes of constructing parent and it seem you are confusing them
The Parent() constructor is always called because you Derived derives from Parent but doesnt include a constructor, hence a default constructor is created, which calls the parameterless parent constructor.
The call to Parent p = new Parent(s); will call the constructor of Parent that takes a parameter.
If you want to call the parent constructor when creating a Derived object, you have to chain the constructors using base().
public class Derived : Parent
{
public void Derived()
: base()
{
//code
}
public void Derived(string s)
:base(s)
{
//code
}
}
I would like to know if it is possible to access the base virtual method using a inheriting class (which overrides the method) object.
I know this is not a good practice but the reason I want to know this is if it is technically possible. I don't follow such practice, asking just out of curiosity.
I did see a few similar questions but I did not get the answer I am looking for.
Example:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}
As per the linked duplicate I commented with, you can do it with some reflection tricks as such:
static void Main(string[] args)
{
Child child = new Child();
Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(Parent).GetMethod("Print").MethodHandle.GetFunctionPointer());
parentPrint.Invoke();
}
Nope - it is not possible to invoke the Virtual method of Base class - The most derived implementation of the method is invoked in such scenarios. In the example given by you, it would print "Print in Child" in both the cases.
According to me, the best you can do is:
public class Parent
{
public virtual void Print()
{
Console.WriteLine("Print in Parent");
}
}
public class Child : Parent
{
public override void Print()
{
base.Print();
Console.WriteLine("Print in Child");
}
}
class Program
{
static void Main(string[] args)
{
Child c = new Child();
//or Parent child = new Child();
child.Print(); //Calls Child class method
((Parent)c).Print(); //Want Parent class method call
}
}
I wouldn't know when this would be helpful. But a decent workaround could be to either overload or write a dummy method that only calls the father class. It would look something like this:
public class Child : Parent
{
public void Print(bool onlyCallFather)
{
if(onlyCallFather)
base.Print();
else
Print();
}
}
And then in your main method:
class Program
{
static void Main(string[] args)
{
Child c = new Child();
child.Print(false); //Calls Child class method
child.Print(true); //Calls only the one at father
}
}
So it would do what you wanted to do. I've actually seen this type of workaround to tell if you want the base method to be called or not.
I have one parent class and one child class.
The parent has a constructor that initializes its parameters.
My question is: How does the child look to the parent's constructor? Can I define a constructor for the children?
you can use base(...) in ctor of your child class.
foreacmple:
public class Child : BaseClass
{
public Child() : base(/*some parameters*/) //CALLING BaseClass parametrized ctor
{
}
}
Just note, if you don't need some specific parameters, just do not do anything, cause BaseClass default ctor will be called by the way when you call ctor of a Child class.
This inheritance sample shows:
how to call the parent constructor from a new constructor on the child
how to pass parameters required by the parent constructor
Code sample:
public class Parent
{
private object _member;
public Parent(object member)
{
this._member = member;
}
}
public class Child : Parent
{
public Child(object member)
: base(member)
{
}
}
You have to define constructors for the children. You can call the base class' constructor using : base() between the constructor prototype and its implementation:
public class Parent {
public Parent() {
...
}
}
public class Child : Parent {
public Child() : base() { // calls Parent.ctor
}
}
Of course.
You are after the "base" keyword.
public class Fruit
{
string TypeOfFruit { get; set; }
public Fruit (string typeOfFruit)
{
TypeOfFruit = typeOfFruit;
}
}
public class Apple : Fruit
{
string AppleType { get; set; }
public Apple(string appleType) : base("Apple")
{
AppleType = appleType;
}
}
You can very well define a constructor for the child class the default one is provided only in case when you do not define a constructor for a class
Meanwhile for how to look up for the constructor of parent
It would check for a parameterless constructor to be present in the parent class and in case you do not have one ( well the compiler lets you know the same) or else you will have to call the parent constructor with the parameters like base("This is the string parameter")
If you meant something else please update the question.