Jun 04

C Derived Class Constructor – An Example:

C derived class constructor has the same name as the name of the class and it does not return any type. A simple piece of code is as follows and this will make you more clear about using the constructor in any software program.

01        class Calc {

02        private:class constructor c

03            int info1;

04            int info2;

05        public:

06            Calc(int i1, int i2) :  info1(i1), info2(i2) { };

07        };

08

09        class Foo : public Calc {

10           int fooData;

11

12           Foo(int i1, int i2, int foo) : Calc(i1, i2), fooData(foo) { }

13        };

Therefore, if you look at the line Calc (int i1, int i2) : info1(i1), info2(i2) { }

This is a constructor and the part info1(i1), info2(i2) are not two new functions, rather these are initialized c class constructorwhich means: “make info1=i1, make info2 = i2″. Since this happens in the initializer list, there is no need for anything in the constructor body, hence all that is left blank.

In Foo the constructor’s initialization list tells the compiler to use the constructor for Calc to initialize the object with i1 and i2, and then to make fooData = foo.

Finally, in order to understand the entire code more clearly, you should copy the program and run it to see if it works accordingly. This practice will make you more clear about how to use the C derived class constructor.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)
Related Posts Plugin for WordPress, Blogger...