20-CS-122-001 Computer Science II Spring 2012
A Simple Class

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Previous      Next      Source      Java version

//  A Simple Class
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

class Simple {
   int number;
	
public:
   Simple() {}
   Simple(int n) { number = n; }
   void display() { cout << "The number is " << number << "\n"; }
   void multiply (int n) { number *= n; }
};

int main () {
   Simple *a = new Simple(100);
   a->display();
   a->multiply(3);
   a->display();
   // a->number = 2;  /* try to access private variable */
   *a = 50;
   a->display();
   
   Simple b(100);
   b.display();
   b.multiply(3);
   b.display();
   Simple *c = &b;
   *c = 50;
   b.display();
	
   *(&b) = 200;
   b.display();
   
   b=400;
   b.display();
}

// Sample Output:
//   The number is 100
//   The number is 300
//   The number is 50
//   The number is 100
//   The number is 300
//   The number is 50
//   The number is 200
//   The number is 400