CS246 Lecture 7: Lesson 7

57 views4 pages

Document Summary

Node * np = new node; struct node { int data; Stack-allocated variables are auto deallocated when they go out of scope eg. function returns. Heap-allocated memory is never auto deallocated and must be deleted stack heap stack local memory for functions heap. Node getmeanode(){ node n; //stack-local return n; //makes a copy for caller, discards local copy int main(){ Node n; //stack return &n; //return address of deallocated node, address invalid. Node * np = newnode; //heap allocated return np; Node* n = getmeanode(); delete n; // remember to deallocate. Operator overloading defining operators (+, *, -) for types you create eg. struct vec{ }add 2 vectors using +, multiply vectors by scalar using x int x,y; Vec operator+ (const vec & v1, const vec & v2){ Vec v {v1. x + v2. x, v1. y + v2. y}; return v; Vec operator* (const vec & v, const int k){ return {v. x*k + v. y*k};

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers