Lecture 9

Class

  • Big innovation in OOP

  • Can put functions inside a struct

Example:

// file: student.h

#ifndef STUDENT_H
#define STUDENT_H

struct student {
  int assns, mt, final;
  float grade(); // forward declaration
};

// file: student.cc

#include "student.h"
float Student::grade() { // veru similar to std::
return this->assns*0.5+this->mt*0.2+this->final*0.4;
}

Student billy {70, 50, 75};
Student billy = {70, 50, 75};
billy.grade();

Class: A struct that contains functions

  • every C++ struct can contain functions

  • An instance/value of a class is called an object

    • I.e. Billy is an object

Member: Function within a class

  • eg. grade(); //invalid

  • Must use object to call a method

  • methods are called on objects

  • Within method call, method has access fields of the object

Methods

  • have hidden parameter

    • "this"

    • "this" points to object used to call method eg.

Style Initialization:

  • requires "parameters" to be compile time constant

  • C++ allows special methods called constructors to construct objects

Example:

Compare:

Advantages of Constructors:

  • args do not need to be constants

  • method overloading (different parameters)

  • ctor body can execute any code

    • ex. sanity checks

  • default args

Example:

Default Constructor

Every class comes with a default ctor

  • ctor with 0 parameters

  • calls default ctors on fields that are objects Example

  • ctor body -> too late to initialize constant

  • Hijack step 2 to intialize constants/references

  • MIL: Members Initialization List

Last updated

Was this helpful?