20-CS-122-001 Computer Science II Spring 2012
Simple Class - But Can Be Tricked

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

Prev      Next      Lectures      Source

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;

// A peculiarity of C++ is that one can peek at
the values anyway
class Simple {  
   char one, two, three, four;

public:

   // Constructor
   Simple (char one, char two, char three, char four) {
      this->one = one;
      this->two = two;
      this->three = three;
      this->four = four;
   }

   // A method
   int sum () {  return one + two + three + four;  }
};
   
int main () {
   Simple *a = new Simple(2,4,64,0);
   cout << "a->one = "   << (int)*(char*)a     << " "
	<< "a->two = "   << (int)*((char*)a+1) << " "
	<< "a->three = " << (int)*((char*)a+2) << " "
	<< "a->four = "  << (int)*((char*)a+3) << "\n";
}