简体   繁体   中英

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. Suppose I do not want to use any variable of class A in child C. Why is the base class constructor getting called?

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.

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.

There is plenty of information on Google on derived classes and how they work. https://www.google.ca/?gws_rd=ssl#q=inheritance+in+object+oriented+programming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM