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
}
}
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
If I have this code in C#:
public abstract class Parent
{
private int x;
public Parent(int x)
{
this.x = x;
}
public abstract void foo;
}
public class Child
{
public override void foo()
{
x = x + 10;
}
}
I get error that:
Parent does not contain constructor that takes 0 arguments.
How can I fix it, without creating non-parametric constructor?
You can create a constructor in Child, e.g.
public Child(int x) : base(x)
{
}
Constructors are not inherited - but if you don't supply any constructors at all, the C# compiler tries to create one equivalent to this:
public Child() : base()
{
}
That's what's failing here, because there isn't a parameterless base constructor to call.
Your derived class constructor doesn't have to have the same parameters as the base class constructor of course - so long as it passes appropriate arguments to a base constructor, that's fine. For example, you could write:
public Child() : base(0) // Default to x = 0
{
}
See my article on constructors for more details.
By manually invoking Parent's constructor:
public class Child: Parent {
public Child( )
: base(0) { }
public override void foo( ) {
x = x + 10;
}
}
That is because there is an Implicit call to a constructor with zero argument.
So you need to add an explicit call:
public Child(int x) : base(x)
{
}
Or instead, you can add zero argument contructor in parent itself:
public parent() { }
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.
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());
}
}
I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
public BaseClass(int someValue) {}
//...more code, not important here
}
and, my proxy resembles:
public BaseClassProxy : BaseClass
{
public BaseClassProxy(bool fakeOut){}
}
Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.
There is a way to create an object without calling any instance constructors.
Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.
This is how you do it:
FormatterServices.GetUninitializedObject(typeof(MyClass));
Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.
When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.
I don't believe you can get around calling the constructor. But you could do something like this:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
protected virtual void Setup()
{
}
}
public BaseClassProxy : BaseClass
{
bool _fakeOut;
protected BaseClassProxy(bool fakeOut)
{
_fakeOut = fakeOut;
Setup();
}
public override void Setup()
{
if(_fakeOut)
{
base.Setup();
}
//Your other constructor code
}
}
If what you want is to not call either of the two base class constructors, this cannot be done.
C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base() { }
}
If you prefer to use the other base class constructor, you can use:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base(someIntValue) { }
}
Either way, one of the two will be called, explicitly or implicitly.
When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:
public BaseClassProxy (bool fakeOut) : base (10) {}
To call the second constructor instead of the first one
I am affraid that not base calling constructor isn't option.
I ended up doing something like this:
public class BaseClassProxy : BaseClass
{
public BaseClass BaseClass { get; private set; }
public virtual int MethodINeedToOverride(){}
public virtual string PropertyINeedToOverride() { get; protected set; }
}
This got me around some of the bad practices of the base class.
constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.
All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work. I was hoping to avoid using this in my class but here it is:
Here is my class constructor:
public MyClass();
{
throw new Exception("Error: Must call constructor with parameters.");
}
OK now you were warned that it was ugly. No complaints please!
I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.
I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor. And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!
It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.
public class MyClass_Base
{
public MyClass_Base()
{
/// Don't call the InitClass() when the object is inherited
/// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!
if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)
{
this.InitClass();
}
}
protected void InitClass()
{
// The init stuff
}
}
public class MyClass : MyClass_Base
{
public MyClass(bool callBaseClassInit)
{
if(callBaseClassInit == true)
base.InitClass();
}
}
Here is my solution to the problem
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(new Child().Test);
}
public class Child : Parent {
public Child() : base(false) {
//No Parent Constructor called
}
}
public class Parent {
public int Test {get;set;}
public Parent()
{
Test = 5;
}
public Parent(bool NoBase){
//Don't do anything
}
}
}
A simple elegant solution. You can change it according to your need.
Another simple solution from me:
class parent
{
public parent()
{
//code for all children
if (this.GetType() == typeof(child1))
{
//code only for objects of class "child1"
}
else
{
//code for objects of other child classes
}
}
}
class child1 : parent
{
public child1()
{}
}
// class child2: parent ... child3 : parent ... e.t.c