Object-Oriented Languages




CS152

Chris Pollett

Mar. 30, 2009

Outline

Introduction

More on ADTs

Quiz

Which of the following would produce a side-effect? (The function call is the statement under consideration).

  1. A call to a function which involves incrementing a non-static local variable.
  2. A call to a function that sets a non-static local variable to one plus the value of a static variable.
  3. A call to a function which increments a global variable.

Object-Orientation Motivated by ADTs

Example C++ Program

#include <iostream>
using namespace std; 
/*use namespace for input/output 
syntax for namespace is
namespace MyName 
{
}

Can use scope resolution MyName:: 
to refer to things in a namespace
*/

class MyContainer
/*
 the syntax for subclasses 
 is class MyClass : Parent {};
 can be comma separated list 
 of parent classes.

 use virtual to say a function 
 can be overriden
*/
{
  private:
    int *myArray;
    int size;

  public:
    MyContainer(int num, int length);
    ~MyContainer();

    void printArray();

}; // notice the semi-colon
/* typically the class would be in a .h 
   file and the following 
   would be in a .cpp file
*/

MyContainer::MyContainer(int num, int length)
{
   myArray = new int[length];
   for(int i=0; i < length; i++)
   {
      myArray[i] = num;
   }

   size = length;
}

MyContainer::~MyContainer() //destructor
{
   delete[] myArray;
}


void MyContainer::printArray()
{
  for(int i = 0; i < size; i++)
  {
     cout << myArray[i]; 
    // cout is C++ way of printing things.
  }

  cout << endl; // a newline
}

int main()
{

  MyContainer test(3, 7);
  // allocates on the stack  

  test.printArray();

  MyContainer *test2 = new MyContainer(4,20);
  test2->printArray();
  // allocates on the heap. 

  return 0;
}

// To compile: g++ filename.cpp

Message Passing and OO

Preserving State the Fortran Way