1.6 Classes

Members

 #include <iostream>
 using namespace std;
 
 class Clock {
   int hr, min, sec;
  public:
   void set( int h, int m, int s )
     { hr = h; min = m;  sec = s; }
   void display()
     { cout << hr << ':' << min << ':' << sec ; }
 };
 
 int main ()
 {    Clock c;
  c.set(11,59,59);  c.display();
  return 0;
 }
-_-_-
Seperated Declarations and Definitions

 
 #include <iostream>
 using namespace std;
 
 class Clock {
    int hr, min, sec;
  public:
    void set( int, int, int );
    void display();
 };
 void Clock::set( int h, int m, int s ) {
    hr = h; min = m;  sec = s;
 }
 void Clock::display() {
    cout << hr << ':' << min << ':' << sec ;
 }
 int main ()
 {    Clock c;
    c.set(11,59,59);  c.display();
    return 0;
 }
Declarations
        class x; ... class x{ ... };

Constructors

 
 class coord{
   int x, y;
     public:
   coord()              { x=0; y=0; }
   coord( int a )       { x=a; y=0; }
   coord( int a, int b ){ x=a; y=b; }
 };
 coord C1 = coord();
 coord C2 = coord(11,12);
 coord C3 = coord(99);

All the newly defined variables must be initialized for types that provide constructors. Optional

 
 class coord{
   int x, y;
     public:
   coord()              { x=0; y=0; }
   coord( int a )       { x=a; y=0; }
   coord( int a, int b ){ x=a; y=b; }
 };
 coord C1;
 coord C2 (11,12);
 coord C3 = 99;
Destructors

The name of a destructor is the name of the class preceded by a tilde character, ‘~’.

 
 #include <iostream>
 using namespace std;
 
 class oranges{
      public:
   int n;
   oranges(){ n = 100; }
   ~oranges(){ cout << n << '\n'; }
 };
 void eat( oranges &A, int a )
 { A.n = A.n - a;
 }
 main(){
   oranges A;
   {  oranges B;  eat(B,11);  }
 }

[Record Types]