Cpp - class Defining Classes

Introduction

Classes in C++ supports object-oriented programming (OOP).

A class defines the properties and capacities of an object.

A class definition specifies the name of the class and the names and types of the class members.

The definition begins with the keyword class followed by the class name.

At the same time, the class members are divided into:

  • private members, which cannot be accessed externally
  • public members, which are available for external access.

The private section generally contains data members and the public section contains the access methods for the data.

This provides for data encapsulation.

class Demo 
{ 
    private: 

               // Private data members and methods here 

    public: 

               // Public data members and methods here 

}; 

The following example includes a class named Account used to represent a bank account.

The data members, such as the name of the account holder, the account number, and the account balance, are declared as private.

There are two public methods, init() for initialization purposes and display(), which is used to display the data on screen.

#include <iostream> 
#include <iomanip> 
#include <string> 
using namespace std; 

class Account 
{ 
    private:                         // Sheltered members: 
      string name;                // Account holder 
      unsigned long nr;           // Account number 
      double balance;             // Account balance 

    public:                          //Public interface: 
      bool init( const string&, unsigned long, double); 
      void display(); 
}; 
bool Account::init (const string& i_name, 
                      unsigned long i_nr, 
                      double        i_balance) 
{ 
   if( i_name.size() < 1)            // No empty name 
          return false; 
   name    = i_name; 
   nr      = i_nr; 
   balance = i_balance; 
   return true; 
} 

// The method display() outputs private data. 
void Account::display() 
{ 
   cout << fixed << setprecision(2) 
         << "Account holder:    " << name  << '\n' 
         << "Account number:    " << nr    << '\n' 
         << "Account balance:   " << balance << '\n' 
         << endl; 
} 

Related Topic