I have a child and a parent class, as such:
class B : A{
public B : base(){
// stuff
}
}
class A{
public A(){
// how can I gain access here to the class that called me,
// ie the instance of class B that's being instantiated.
}
}
As above, my question is whether I can see who called the parent constructor within the constructor of the parent class.
One way to do this would be to have a separate function in A to which you pass this from within B. Is there anything simpler, ie can I do this during object initialization, or is that too early in the object construction process ? Does the whole object B need to be “ready” before I can access it from within A ?
Thanks!
Within
A, it’s easy – you just usethisand cast it toBif you’re confident that it really is aBrather than any other derived class. The object will already an instance ofB.However, it’s generally a bad idea to call virtual methods from constructors, as the body of the B constructor hasn’t been run yet, so it’s only half-initialized. I’ve had a few situations where this is a pain, but if you tell us what you’re trying to achieve we may be able to come up with something cleaner.