[英]Why is the base class and derived class constructor getting called when creating object of the child class
Code :
class A
{
public A()
{
}
}
class B : A
{
public B()
{
}
}
class C : B
{
public C()
{
}
}
Main()
{
C a =new C();
}
When creating a new object C, first the class A constructor is called, then the class B constructor, then finally the class C constructor.创建新对象 C 时,首先调用 A 类构造函数,然后是 B 类构造函数,最后是 C 类构造函数。 Suppose I do not want to use any variable of class A in child C. Why is the base class constructor getting called?假设我不想在子 C 中使用 A 类的任何变量。为什么要调用基类构造函数?
Your base class constructors are being called because you've derived the child classes from the base classes.您的基类构造函数被调用是因为您已经从基类派生了子类。 By definition the child classes inherit the member variables and functions of their base class.根据定义,子类继承其基类的成员变量和函数。 You should probably read up more on how object oriented inheritence works.您可能应该阅读更多关于面向对象继承如何工作的信息。
Let's take an example.让我们举个例子。 Say you in your program you are dealing with people.假设你在你的程序中与人打交道。 You create a people class with a constructor and member variables name, age, and gender.您创建一个带有构造函数和成员变量名称、年龄和性别的人员类。 You can instantiate this into as many people as you want.您可以将其实例化为任意数量的人。
Then you want further functionality in your program and you create two new classes, one for Students, and one for Employees.然后,您希望在程序中具有更多功能,并创建两个新类,一个用于学生,另一个用于员工。
With students, you want name, age, gender, grade, major and year and with Employees you want name, age, gender, position, salary.对于学生,您需要姓名、年龄、性别、年级、专业和年份,而对于员工,您需要姓名、年龄、性别、职位、薪水。
The two new classes: Students and Employees are derived from the Person class because they need name, age, and gender.两个新类:Students 和Employees 派生自Person 类,因为他们需要姓名、年龄和性别。
If you do not want the class C to have it's base class created all you need to do is not have class C inherit class B.如果您不希望类 C 创建它的基类,那么您需要做的就是不要让类 C 继承类 B。
There is plenty of information on Google on derived classes and how they work. Google 上有大量关于派生类及其工作方式的信息。 https://www.google.ca/?gws_rd=ssl#q=inheritance+in+object+oriented+programming https://www.google.ca/?gws_rd=ssl#q=inheritance+in+object+oriented+programming
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.