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

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 no longer looking like a struct because its data members
// are now private (invisible to objects).  The constructor now is the
// only way to assign values to the variables.  The method still works
// because it can see the variables.
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 << "\nSum = " << a->sum() << "\n";
}