0% found this document useful (0 votes)
19 views

Constructors

Constructors are special member functions that are automatically called to initialize objects whenever they are created. Constructors must have the same name as the class, do not have a return type, and are used to set initial values for object attributes. For example, a default constructor for a Test class that initializes integer data members x and y to 0 would be declared without parameters as Test::Test() and called automatically whenever a Test object is created.

Uploaded by

Harshida Patel
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Constructors

Constructors are special member functions that are automatically called to initialize objects whenever they are created. Constructors must have the same name as the class, do not have a return type, and are used to set initial values for object attributes. For example, a default constructor for a Test class that initializes integer data members x and y to 0 would be declared without parameters as Test::Test() and called automatically whenever a Test object is created.

Uploaded by

Harshida Patel
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Constructors: A constructor is a special member function for automatic initialization of an object whenever an object is created, the special member

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.

You might also like