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

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

Prev      Next      Lectures      Source

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

// A simple class, looking like a struct except that a constructor
// is added to initialize an object's variables.
class Simple {  
public:
   char one, two, three, four;

   // Constructor
   Simple (char one, char two, char three, char four) {
      this->one = one;
      this->two = two;
      this->three = three;
      this->four = four;
   }
};
   
int main () {
   Simple *a = new Simple(2,4,64,0);
   
   cout << "\nValue of a.numbers: "
        << (int)a->one << " " 
        << (int)a->two << " "
        << a->three << " "
        << (int)a->four << "\n";
   cout << "Addresses:\n"
	<< " a->one=" << (unsigned long)&a->one
	<< " a->two=" << (unsigned long)&a->two
	<< " a->three=" << (unsigned long)&a->three
	<< " a->four=" << (unsigned long)&a->four
	<< "\n";
   // 00000010 00000100 01000000 00000000
   //     2   +  1024  + 4194304 +  0  = 4195330
   printf("Value of a: %u\n", *(unsigned long*)a);
}