COMS 3157 Advanced Programming

Index of 2024-1/code/23

Parent directory
hello.cpp

hello.cpp

#include <stdio.h>

class Pt {
public:
    double x;
    double y;

    Pt() {
        x = 1.0;
        y = 2.0;
    }

    ~Pt() {
        printf("bye\n");
    }

    void print() {
        printf("(%g,%g)\n", this->x, y);
    }
};

/* Equvalent C functions:

void Pt_ctor(struct Pt *this) {
    this->x = 1.0;
    this->y = 2.0;
}

void Pt_print(struct Pt *this) {
    printf("(%g,%g)\n", this->x, this->y);
}
*/

int main()
{
    // Stack allocation of object in C++
    // Declaring a reference (i.e. pointer) in Java

    Pt p;

    /* Heap allocations:

    // in Java
    Pt pp = new Pt();

    // in C++
    Pt *pp = new Pt();
    ...
    delete(pp);

    // in C
    Pt *pp = malloc(sizeof(struct Pt));
    Pt_ctor(pp)
    ...
    free(pp);

    */

    p.print(); // Pt_print(&p);
}