Lecture 3

Class definition

The header file defines a class. Example:

#ifndef STACK_H
#define STACK_H
  
class Stack{
public:
  Stack(int size);
  
  // destructor
  ~Stack();
  
  void push(int i);
  int pop();
  
private:
  int stack_size;
  int* stck;
  int tos;
};

Members (Data and functions) defined after public, can be accessed by functions outside the class. Members defined after private can only be accessed by functions that are members of the class, or are declared to be friends of the class.

A constructor is a special ember function of a class and has the same name as that class. It can have parameters or be parameter-less, can be overloaded, and can't have a return type. It is automatically called when an object of the class is created, to provide initialisation as appropriate.

The destructor has the same name as the class, but it is preceded by a ~. It can't have parameters or a return type. It is called automatically when an object is destroyed or out of scope, to undo what the constructor does. For example, it will deallocate dynamic memory previously allocated (otherwise the program will suffer from a memory leak), or to close a file that had been opened, etc.

Integer stack

#ifndef ISTACK_H
#define ISTACK_H

class intStack {
public:
  // Constructor
  intStack(int size);
  
  // Destructor
  ~intStack();
  
  //public members (Data or functions)
  void push(int i);
  int pop();
  
private:
  int* data;
  int tos; // Top of stack
  int stack_size;
};
  
#endif

The . and -> operators

Accessing members for an object is done by using the . operator. Accessing members for pointers is done using the -> operator.

.

int main() {
	Stack s(3);
    
    s.push(10);
    std::cout << s.pop() << std::endl;
    
    return 0;
}

->

int main(){
  Stack* s = new Stack(3);
  
  s->push(10);
  
  std::cout << s->pop() << std::endl;
}

Dynamic array of objects

No array allocated by new can have an initialising parameters. To use dynamic arrays of objects, a parameter-less constructor must be created. Stack()

Static Class Members

Each object of a class keeps an individual copy of the members of that class. When you precede a data member's declaration with static, you tell the compiler that only one copy of that member will exist, and that all objects of that class will share that member.