Cpp classes

From wikinotes


Classes are like struct datatypes, except in addition to datatypes, you can have functions as methods. (although you can use the constructor struct interchangeably with class)


Unlike python, there are 3 types of methods/attributes in cpp:

  • private (only members of same class can see) (default)
  • protected (only members of same class, and inherited classes can see)
  • public (anyone can see)


in cpp methods, this behaves similarly to self. It is a pointer to the class. So you can access attributes internally by means of this->attr.


Class Definition

Also unlike python in order to keep your class definitions legible (like an index), it is considered a best practice to store your long function definitions outside of the class.

/*
 * Methods defined outside of class
 */

class Vehicle {
    // class variables (static)
    int wheels;
    int gas_mileage;
    int remaining_fuel;

    private:
        int _calculate_fuel_efficiency_rating();
    protected:
        void drive(int);
    public:
        int get_remaining_fuel();
};


int Vehicle::_calculate_fuel_efficiencty_rating(){
    return 10;
}

void Vehicle::drive(int gas_pressure){
    int fuel = this->get_remaining_fuel();
    return 10;
}

int get_remaining_fuel() {
    return Vehicle::remaining_fuel;
}


Instantiation/Usage

You can use objects in two ways - either instantiate them on the stack, or save them in memory and keep a reference to the object.

on Stack:


WARNING:

MyClass object(); is illegal. Do not use parentheses unless needed.

MyClass object;                        // instantiate object on the stack
MyClass object("paramA", "paramB");    // same, with arguments
object.setText("mytext");              // call method on obj on stack

in Memory:

MyClass *object = new MyClass();  // keep reference to object
object->setText("mytext");        // call method on pointer