NIOS Computer: Chapter 13 – Classes & Objects with Constructors/Destructors Part 1

Download PDF of This Page (Size: 459K)

Image of constructors and destructors

Image of Constructors and Destructors

Image of constructors and destructors

Introduction

In object oriented programming, the emphasis is on data rather than function.

Constructor is a specially designed class and destructor returns the memory addresses back to the system.

Objectives

  • After going through this lesson, you would be able to

  • Define class and object l access the members of the class

  • Learn about three visibility modes: public, private and protected

  • Familiarize with constructor and its types

  • Define constructor with default arguments

  • Use destructor.

Class

A class is way to bind the data and its associated functions together. It allows data functions to be hidden, if necessary from external use.

A class specification has two parts.

(i) Class declaration

(ii) Class function definitions

The general format of a class declaration is

  1. class class-name
  2. {
  3.     private :
  4.     Variable declarations;
  5.     Function declarations;
  6.     public:
  7.     Variable declarations;
  8.     Function declarations;
  9.     protected :
  10.     Variable declarations;
  11.     Function declarations;
  12. };

The keyword class is followed by the name of the class. The body of the class is enclosed between braces and terminated by semi-colon.

The class body contains the declaration of variables and functions. These are collectively called members.

The variables declared inside the class are called data members.

The functions are known as member functions. The keywords public, private and protected are called visibility modes.

The use of keyword private is optional.

By default, the members of a class are private. If the labels are missing, members are private by default.

Such a class is completely hidden from outside world and does not serve any function.