Department of Computer Science



next up previous
Next: C++Basic Components and Layout Up: C++ Previous: C++


C++ after Java or Eiffel


C++ is an object oriented language like Java, Eiffel and others. They all have classes, inheritance and subtyping, so you can design programs in very similar ways in all languages, the structures will be similar. However there are lots of differences:

There follows a trivial program written in both Eiffel and C++. It defines a class Account, declares an Account object and then invokes a couple of operations on it. The programs are followed by some notes on the similarities and differences.

  1 class ACCOUNT
  2 creation make
  3 feature{ANY}
  4   owner: string
  5   balance: real
  6 
  7   make(o: string) is
  8   do balance := 0.0
  9      owner := o
 10   end
 11 
 12   deposit(n: real) is
 13   do balance:=balance+n; end
 14 
 15   withdraw(n: real) is
 16   do if  balance-n >= 0 
 17      then
 18        balance := balance-n
 19      end
 20   end
 21 end -- ACCOUNT
 22 
 23 ---- in another file-----
 24 class TESTACCOUNT
 25 creation make
 26 feature
 27   kitty: ACCOUNT
 28 
 29   make is 
 30   do
 31     !!kitty.make("beer money")
 32     kitty.deposit(2.0)
 33     kitty.withdraw(0.7)
 34     io.put_string("balance: ")
 35     io.put_real(kitty.balance)
 36     io.put_string("%N")
 37   end
 38 end -- TESTACCOUNT
  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4
  5 class Account {
  6   private:
  7     string name;
  8     double amount;
  9   public:
 10     Account(string o){
 11       name = o;
 12     }
 13     double balance(void) {
 14       return amount;
 15     }
 16     void deposit(double n) {
 17       amount = amount + n;
 18     }
 19     string owner(void) {
 20       return name;
 21     }
 22     void withdraw(double n) {
 23       if ( amount-n >= 0 )
 24          amount = amount - n;
 25     }
 26 };
 27
 28 int main( ) {
 29   Account kitty("beer fund");
 30 
 31   kitty.deposit(2.0);
 32   kitty.withdraw(0.7);
 33   cout << "balance: "
 34        << kitty.balance() 
 35        << "\n";
 36 }


(Programs in account.e, testaccount.e and account.cpp).
Notes on the two programs:


next up previous
Next: C++Basic Components and Layout Up: C++ Previous: C++


Page generated: 2002-11-04 by Bob Dickerson

© University of Hertfordshire Higher Education Corporation (1998)

Disclaimer