1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn about C++ Classes and Objects

By , About.com Guide

3 of 9

More about the Book Class

In C++, the constructor always has the same name as the class. The constructor is called when the object is created and is where you should put your code to initialize the object.

In Book The next line after the constructor the destructor. This has the same name as the constructor but with a ~ (tilde) in front of it. During the destruction of an object, the destructor is called to tidy up the object, and ensure that resources such as memory and file handles used by the object are released.

Remember : A class xyz has a constructor function xyz() and destructor function ~xyz(). Even if you don't declare then the compiler will silently add them.

The destructor is always called when the object is terminated. In this example the object is implicitly destroyed when it goes out of scope. To see this, modify the destructor declaration to this.

~Book(){ std::cout << "Destructor called\n";} ; // Destructor
This is an inline function with code in the declaration. Another way to inline is adding the word inline.
inline ~Book() ; // Destructor
and add the destructor as a function like this.
inline Book::~Book ( void ) {
std::cout << "Destructor called\n";
}
Inline functions are hints to the compiler to generate more efficient code. They should only be used for small functions, but if used in appropriate places such as inside loops can make a considerable difference in performance.

On the next page : Learn more about class methods

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. More about the Book Class

©2009 About.com, a part of The New York Times Company.

All rights reserved.