Constructors and Destructors

In C++, a class may contain a constructor function, a destructor function, or both. A constructor is called when an object of the class is first created and the destructor is called when an object of the class is destroyed. A constructor has the same name as the class of which it is a member and the destructor’s name is the same as its class, except that it is preceded by a ~. Neither constructors nor destructors have return values.

Constructors may have parameters. You can use these parameters to pass values to a constructor, which can be used to initialize an object. The arguments that are passed to the parameters are specified when an object is created. For example, this fragment illustrates how to pass a constructor an argument:

class myclass {   int a; public:   myclass(int i) { a = i; } // constructor   ~myclass() { cout << "Destructing..."; } }; // ... myclass ob(3); // pass 3 to i

When ob is declared, the value 3 is passed to the constructor’s parameter i, which is then assigned to a.

In an inheritance hierarchy, a base class’ constructor is automatically called before the derived class’ constructor. If you need to pass arguments to the base class constructor, you do so by using an expanded form of the derived class’ constructor declaration. Its general form is shown here:

 derived-constructor(arg-list) : base1(arg-list),                                 base2(arg-list),                                   // ...                                baseN(arg-list)  {   // body of derived constructor } 

Here, base1 through baseN are the names of the base classes inherited by the derived class. Notice that a colon separates the derived class’ constructor declaration from the base class specifications, and that the base class specifications are separated from each other by commas, in the case of multiple base classes. Here is an example:

class base { protected:   int i; public:   base(int x) { i = x; }   // ... }; class derived: public base {   int j; public:   // derived uses x; y is passed along to base.   derived(int x, int y): base(y) { j = x; }   void show() { cout << i << " " << j << "\n"; }   // ... };

Here, derived’s constructor is declared as taking two parameters, x and y. However, derived( ) uses only x; y is passed along to base( ). In general, the derived class’ constructor must declare the parameter(s) that it requires as well as any required by the base class. As the example illustrates, any values required by the base class are passed to it in the base class’ argument list specified after the colon.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: