Constructors
Constructors
function i.e. the constructor will be executed automatically. The syntax rules for writing constructor function are: (1) They should be declared in public section. (2) A constructor name must be the same as that of its class name. (3) It is declared with no return type (not even void). (4) It may be not static. (5) It may not virtual. The general syntax of constructor function is: Class class-name { public: class-name(); //constructor declaration or definition --------------}; class-name::class-name() //constructor definition { ----} e.g. class test { int x,y; public: test() {x=0;y=0;} }; Therefore the declaration Test A; //object is created Not only creates the object A of type test but also initializes its data members x and y to zero. There is no need to write any statement to invoke the constructor function. A constructor that accepts no parameters is called the default constructor. e.g. test :: test(); The constructor functions have some special characteristics: (1) They are invoked automatically when the objects are created. (2) They should be declared in the public section. (3) They do not have return type. (4) Constructor cannot be virtual. (5) They make implicit calls to the operator new and delete when memory allocation is required. (6) We cannot refer to their addresses. (7) They cannot be inherited.