C++ Classes

A Complex Number Class

  
  class Complex
  {
  private:
      double re;
      double im;
  
  public:
      Complex(float r,float i) {re = r; im = i;}
      Complex(float r) {re = r;im = 0.0;}
      ~Complex() {};
  
      double Magnitude();        // calculate magnitude
        
      double Real() {return re;} // return real part
      inline double Imag();      // return imaginary part
  
      Complex operator+(Complex b)
      {return Complex(re + b.re,im + b.im);}
  
      Complex operator=(Complex b)
          {re = b.re;im = b.im; return *this;}
  };
  
  inline double Complex::Imag()
  {
      return im;
  }
  
  double Complex::Magnitude()
  {
      return sqrt(re*re + Imag()*Imag());
  }
  
  

Access Control

Constructors

Destructors

Usage

  
  #include 
  #include "Complex.h"
  
  main()
  {
      Complex a(1.0,1.0);
      Complex b(5.0);
  
      printf("a real = %f  a imaginary = %f\n",a.Real(),
                                               a.Imag());
      printf("b real = %f  b imaginary = %f\n",b.Real(),
                                               b.Imag());
  }
  
  

  
  #include 
  #include "Complex.h"
  
  main()
  {
      Complex *a;
      Complex *b = new Complex(5.0);
      Complex c(0,0);
  
      a = new Complex(1.0,1.0);
      c = a + b;
  
      printf("a real = %f  a imaginary = %f\n",a->Real(),
                                               a->Imag());
      printf("c real = %f  c imaginary = %f\n",c.Real(),
                                               c.Imag());
  
      delete a;
      delete b;
  }
  
  

Operator Functions

Casting Functions

Derived Class

Derived Class Example

  
  class Employee
  {
     char* name;
     int age;
     int department;
     int salary;
  
  public:
     Employee(char* name);
     void print();
  };
  
  
  class Manager : public Employee
  {
     EmployeeList employees;
  
  public:
     Manager(char* name, Employee* people);
     void print();
  };
  
  

Derived Class Operation

Deriving Multiple Classes

Virtual Functions